MVC .NET Model Binding to Array on the fly

烈酒焚心 提交于 2019-12-17 18:58:52

问题


In Scotts blog post he describes how to post an array of objects to the controller.

My Question how best to generate a View for this that allows the user to add more array items on the fly?

If I write

 foreach(MyModel item in Model)
 {
     <p>@Html.TextBoxFor(m => item.Name)</p>
 }

and have the controller add a new item to the array each time it generates <input type="text" name="item.Name" /> missing the 1 Array index.

If I hand code the <input> then it works but I lose all the client side validation attributes like data-val-required="Name is required"

What I want to be able to do is have the User add new Items to the array on the fly and still retain unobtrusive validation?. What's the best practice for this?

I am thinking I have write it myself using jQuery but if so can I keep the validation?

Update Seems like Tassadaque answer is a nice .NET solution but looks like a lot of server side code to do something which should be very easy. Muhammad Adeel Zahi answer is ok but still misses out client side validation.

I think I will end up just writing my own client side HTML manually and using jQuery live and validation plug-in. So I can do all my own validation and adding and removing of new Items all client side without any calls to the server.


回答1:


You may see This In this post steve Validated a variable length list in which textboxes may be added or deleted dynamically




回答2:


when rendering and binding to lists or arrays, i normally prefer for loop over foreach loop because it will generate required indices for the modelbinder to bind data to the model.

for(int i=0;i<Model.Count(); i++)
{
   <%:Html.TextBox("Items["+i+"].Name", Model[i].Name)%>
}

i m not comfortable with strongly typed helpers when it comes to list binding but its purely a matter of personal preference. However, if you are allowing the user to dynamically add and remove items from page through javascript you have to take care of indices yourself.

EDIT: i have blogged about creating master detail form in asp.net mvc using jquery templates which is relevant in list binding scenario as well



来源:https://stackoverflow.com/questions/5496593/mvc-net-model-binding-to-array-on-the-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!