balexandre
balexandre

Reputation: 75093

Understanding Forms in MVC: How can I populate the model from a List<>

Conclusion in Images, can be found in the bottom


I'm having some trouble to get how Forms work in MVC (as I'm a WebForms Developer and really wanna start using MVC in one big project)

I took the MVC2 Web Project and add a simple ViewModel to it

namespace TestForms.Models
{
    public class myFormViewModel
    {
        public myFormViewModel() { this.Options = new List<myList>(); }

        public string Name { get; set; }
        public string Email { get; set; }

        public List<myList> Options { get; set; }
    }

    public class myList
    {
        public myList() { this.Value = this.Name = ""; this.Required = false; }

        public string Name { get; set; }          
        public string Value { get; set; }      
        public string Type { get; set; }
        public bool Required { get; set; }
    }
}

Created a Strongly Typed View, passed a new object to the view and run it.

When I press submit, it does not return what's in the Options part... how can I bind that as well?

my view

alt text http://www.balexandre.com/temp/2010-10-11_1357.png

filling up the generated form

alt text http://www.balexandre.com/temp/2010-10-11_1353.png

when I press Submit the Options part is not passed to the Model! What am I forgetting?

alt text http://www.balexandre.com/temp/2010-10-11_1352.png



Conclusion

Changing the View loop to allocate the sequential number, we now have

<%= Html.TextBox("model.Options[" + i + "].Value", option.Value)%>

model is the name of our Model variable that we pass to the View Options is the property name that is of type List and then we use the property name

alt text

alt text

Upvotes: 2

Views: 633

Answers (1)

Lorenzo
Lorenzo

Reputation: 29427

Looking at your UI it seems that you did not put the data from the Options member on it.

<% foreach (myList obj in Model.Options) { %>
     // Add the object to your UI. they will be serialized when the form is submitted
<% } %>

Also check that you enclose the data in a form element

EDIT:

Sorry! I did'nt realized that you was filling the object inside the controller. Can you please show the code you have in the view?

Upvotes: 2

Related Questions