它比这简单得多,只需在您的输入中添加一个 name='' 约定,mvc 的绑定器将获取这些值。
您实际上有两种选择... 1. name="textbox[0].Name" 等等。2. 创建您自己的 Binder,并根据需要绑定您的输入。你不必重新发明任何东西。
对不起,我花了这么长时间来编辑我的答案,这里是例子:模型:
public class Person
{
public Person()
{
InterestList = new List<Interest>();
}
public IList<Interest> InterestList { get; set; }
}
public class Interest
{
public string Name { get; set; }
}
粘合剂:
public class InterestListBinder: IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var person = new Person();
foreach (var i in controllerContext.RequestContext.HttpContext.Request.Form.AllKeys)
{
person.InterestList.Add(new Interest
{
Name = controllerContext.RequestContext.HttpContext.Request.Form[i]
});
}
return person;
}
}
附加活页夹的 Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(Person), new InterestListBinder());
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Person person)
{
return View("Index", person);
}
}
现在的观点:
@model Data.Services.DataBinders.Person
<div>
<form action="@Url.Action("Index", "Home")" method="POST">
@{
if (Model != null && Model.InterestList.Any())
{
foreach (var tb in Model.InterestList)
{
<input type="text" value="@tb.Name"/>
}
}
}
<input type="button" value="add" id="add" />
<input type="button" value="remove" id="remove" />
<input type="submit" value="Submit" />
</form>
</div>
而生成动态输入的 javascript,您可以输入任何您喜欢的名称:
<script>
(function ($) {
var demo = {
init: function () {
this.elements = null;
this.cache();
this.bindEvents();
return this;
},
cache: function () {
this.elements = new Array();
},
bindEvents: function () {
$("#add").on("click", this.add);
$("#remove").on("click", this.remove);
},
add: function () {
var self = demo;
var $elem = $("<input type='text' \>");
self.elements.push($elem);
self.render();
},
remove: function () {
var self = demo;
$.each(self.elements, function (index, elem) {
elem.remove();
});
self.elements.splice(0, 1);
self.render();
},
render: function () {
var self = demo;
for (var e in self.elements) {
self.elements[e].attr("name", "Interest" + e);
$("form").append(self.elements[e]);
}
console.log(self.elements);
}
};
window.load = demo.init();
})(jQuery)
</script>