ASP.net,MVC 2 - 发布viewModel

时间:2010-07-08 14:03:30

标签: c# asp.net asp.net-mvc

我的问题是,当我提交表单并返回类型为QuestionViewModel的viewModel时--Type为null。

见下面的代码。

我的控制器:

    public ActionResult Create() 
    {
        var viewModel = new QuestionViewModel {  
            Question = question,  
            Type = questionType,  
            Types = surveyDB.QuestionTypes.ToList()  
        };  
        return View(viewModel);  
    }

在我看来:
`

<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>

<% } %>

`

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>

model.Type的编辑

<%: Html.LabelFor(model => model.Alternative) %>
<%: Html.TextAreaFor(model => model.Alternative, new { @Class="alternatives" })%>
<%: Html.ValidationMessageFor(model => model.Alternative)%>

当我现在提交时,我最终到了这里:

    [HttpPost]
    public ActionResult Create(QuestionViewModel viewModel)
    {
        **// This becomes null**
        string alternatives = viewModel.Type.Alternatives;
    }

我的viewmodel看起来像这样

namespace ASurvey.ViewModels {
    public class QuestionViewModel {
        public Question Question { get; set; }
        public List<QuestionType> Types { get; set; }
        public MultipleChoice Type { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

在问题编辑器中,您有代码Html.DropDownList("Type" ...。看起来它会覆盖你的QuestionViewModel.Type编辑器。

尝试在问题编辑器中使用Html.DropDownListFor(x => x.Type ...。它将名称属性呈现为“Question.Type”,但不仅仅是“Type”。