开发者

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.

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()) {%>
    &l开发者_开发百科t;%: 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

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

<%: 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.

Try to use Html.DropDownListFor(x => x.Type ... in Question editor. It will render name attribue as "Question.Type", but not just "Type".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜