It much simpler than that, just add a name='' convention to your inputs and the binder of mvc will get the values.
You actually have two options to do so...
1. name="textbox[0].Name" and so on.
2. Create your own Binder,
and bind your inputs as you need.
You don't have to reinvent nothing.
Excuse me for taking so long to edit my answer, here is the example:
The Models:
public class Person
{
public Person()
{
InterestList = new List<Interest>();
}
public IList<Interest> InterestList { get; set; }
}
public class Interest
{
public string Name { get; set; }
}
The Binder:
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;
}
}
The Global.asax to attach binder
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());
}
}
The Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Person person)
{
return View("Index", person);
}
}
And now the view:
@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>
And the javascript that generates the dynamic inputs, you can put any name you like:
<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>
FormCollectiontennis,foot,ball, andbaseball?nameand in controller access it byFormCollectionand it will have array values. Check FormCollection