Question

I'm add a list of questions to a view model that has that property in it as a list and sending it to the view. I can do a foreach loop and display all the questions on the screen but when I click submit on the form and send that view model to the controller list of questions is empty, I'm not sure how to add those questions back to the view model.

Adding the list to the VM.

AddEditListingViewModel AELVM = new AddEditListingViewModel
        {
            ListingQuestions = new List<ListingDetailQuestionViewModel>(),
            States = states,
            Cities = cities,
            Agents = agents,
        };

        foreach (ListingDetailQuestionViewModel question in questions)
        {
            ListingDetailQuestionViewModel LDQVM = new ListingDetailQuestionViewModel
            {
                QuestionGuid = question.QuestionGuid,
                QuestionNumber = question.QuestionNumber,
                Question = question.Question,
                QuestionSideNotes = question.QuestionSideNotes
            };

            AELVM.ListingQuestions.Add(LDQVM);
        }

        return View("AddNewListing", AELVM);

In the view.

@foreach (ListingDetailQuestionViewModel value in Model.ListingQuestions)
                    {
                        @Html.Label(value.Question + "?", new {Id = value.QuestionGuid})
                        @Html.Label("Answer: ")@Html.TextBox("Answer", "", new {Id = value.QuestionGuid})
                        <br/>
                    }

view is strongly typed for this view model. I can open the list and see the values but when the form is submitted all the questions are null.

Était-ce utile?

La solution

Read up on Model Binding To A List - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx.

You need to use the helper For extension methods to generate html elements with indexed names.

@for (var i = 0; i < Model.ListingQuestions.Count; i++)
{
    @Html.HiddenFor(m => Model.ListingQuestions[i].QuestionGuid);
    @Html.LabelFor(m => Model.ListingQuestions[i].Answer);
    @Html.TextBoxFor(m => Model.ListingQuestions[i].Answer)

Having a look at the HTML this should produce something along the lines of

<input name="ListingQuestions[0].QuestionGuid" type="hidden" value="..." />
....label
<input name="ListingQuestions[0].Answer" type="text" value="" />
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top