MVC .NET 模型动态绑定到数组 [英] MVC .NET Model Binding to Array on the fly

查看:27
本文介绍了MVC .NET 模型动态绑定到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scotts 博客 post 中,他描述了如何将对象数组发布到控制器.

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?

如果我写

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

并让控制器在每次生成 <input type="text" name="item.Name"/> 缺少 1 数组索引.

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.

如果我手动编写 <input> 然后它可以工作,但我丢失了所有客户端验证属性,例如 data-val-required="Name is required"

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?

我想我已经使用 jQuery 自己编写了它,但如果是这样,我可以保留验证吗?

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

更新似乎 Tassadaque 的答案是一个不错的 .NET 解决方案,但看起来像很多服务器端代码来做一些应该很容易的事情.Muhammad Adeel Zahi 的回答没问题,但仍然错过了客户端验证.

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.

我想我最终只会手动编写自己的客户端 HTML 并使用 jQuery 实时和验证插件.因此,我可以进行所有自己的验证,并在所有客户端添加和删除新项目,而无需对服务器进行任何调用.

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.

推荐答案

你可能会看到 这个 在这篇文章中,史蒂夫验证了一个可变长度列表,其中可以动态添加或删除文本框

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

这篇关于MVC .NET 模型动态绑定到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆