1

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()) {%>
    <%: 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; }
    }
}
1
  • 1
    Does MultipleChoice has default constructor so that MVC can create it? You did not post all the code. Commented Jul 8, 2010 at 14:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.