[英]ASP.net, MVC 2 - Posting viewModel
My problem is that when I submit the form and returning my viewModel of type QuestionViewModel - the Type is null. 我的问题是,当我提交表单并返回类型为QuestionViewModel的viewModel时,Type为null。
See code below. 请参见下面的代码。
My controller: 我的控制器:
public ActionResult Create()
{
var viewModel = new QuestionViewModel {
Question = question,
Type = questionType,
Types = surveyDB.QuestionTypes.ToList()
};
return View(viewModel);
}
In my View: 在我看来:
` `
<h2>Skapa en fråga</h2>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<%:Html.EditorFor(model => model.Question, new { Types = Model.Types }) %>
<% switch (Model.Question.Type) {
case 1:
Response.Write(Html.EditorFor(model => model.Type));
break;
default:
break;
}
%>
<p>
<input type="submit" value="Skapa" />
</p>
<% } %>
` `
Where the Editor for model.Question is model.Question的编辑器在哪里
<%: Html.LabelFor(model => model.Type) %>
<%:Html.DropDownList("Type", new SelectList(ViewData["Types"] as IEnumerable,"Id","Type", Model.Type), "Välj en frågetyp")%>
<% if((int)ViewData["type"] > 0) { %>
<div class="editor-label">
<%: Html.LabelFor(model => model.Text) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Text) %>
<%: Html.ValidationMessageFor(model => model.Text) %>
</div>
And the Editor for model.Type 以及model.Type的编辑器
<%: Html.LabelFor(model => model.Alternative) %>
<%: Html.TextAreaFor(model => model.Alternative, new { @Class="alternatives" })%>
<%: Html.ValidationMessageFor(model => model.Alternative)%>
When I now submit I end up here: 当我现在提交时,我将在这里结束:
[HttpPost]
public ActionResult Create(QuestionViewModel viewModel)
{
**// This becomes null**
string alternatives = viewModel.Type.Alternatives;
}
My viewmodel looks like this 我的视图模型看起来像这样
namespace ASurvey.ViewModels {
public class QuestionViewModel {
public Question Question { get; set; }
public List<QuestionType> Types { get; set; }
public MultipleChoice Type { get; set; }
}
}
In your Question editor you have code Html.DropDownList("Type" ...
. Looks like it overrides your QuestionViewModel.Type editor. 在问题编辑器中,您具有代码Html.DropDownList("Type" ...
看起来它覆盖了QuestionViewModel.Type编辑器。
Try to use Html.DropDownListFor(x => x.Type ...
in Question editor. It will render name attribue as "Question.Type", but not just "Type". 尝试在问题编辑器中使用Html.DropDownListFor(x => x.Type ...
它将把名称属性呈现为“ Question.Type”,而不仅仅是“ Type”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.