开发者

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 f开发者_JAVA百科orgetting?

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

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

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


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?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜