I have a requirement to dynamically create objects in my Razor View
and after the user edits them, submit them back to the server.
This is how my model looks like:
public class Panel
{
public string Name { get; set; }
public string Text1 { get; set; }
public string Text2 { get; set; }
}
What I want to do is to render the required inputs each time the clicks on a button using Javascript
. this is how my main view looks like:
@model IEnumerable<TabsTest.Models.Panel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@for (int i = 0; i < ViewBag.I; i++)
{
@*@Html.Partial("_view", new TabsTest.Models.Panel() { Name = "A" + i })*@
@Html.Action("PanelSub", "Panels", new { name = i })
<hr />
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
The PartialView
:
@model TabsTest.Models.Panel
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Text1, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Text2, new { htmlAttributes = new { @class = "form-control" } })
And my Actions:
public ActionResult CreatePanels()
{
ViewBag.I = 5;
return View();
}
[HttpPost]
public ActionResult CreatePanels(IEnumerable<Panel> panels) // <= always returns Null
{
//handle collection...
return RedirectToAction("Index");
}
public PartialViewResult PanelSub(int name = -1)
{
var panel = new Panel() { Name = name.ToString() };
return PartialView("_view");
}
My question is how can I use the model binding to handle the new objects that the user created in the view?