Model: First you need to have properties (with get set both)
public class Foo
{
public string Name
{
get; set;
}
public List<Bar> BarList
{
get; set;
}
}
public class Bar
{
public string Name{
get; set;
}
}
View:
In MVC if the name of any html control is in sync with the model then value of that html control will be automatically bind to that property.
@model Foo
@using (Html.BeginForm("Index", "Default", FormMethod.Post))
{
<span> Name:</span>
@Html.TextBoxFor(m => m.Name)
<span> List of Bars</span>
for (int i = 0; i < 10; i++)
{
@Html.TextBoxFor(m => m.BarList[i].Name)
//or
// <input type="text" name="BarList[@i].Name" />
}
<input type="submit" value="save" />
}
click the button (submit form) and complete data will be bind to the foo parameter of your action .
Controller:
[HttpPost]
public ActionResult Index(Foo foo)
{
return View();
}
Edited:
If you want to add dynamic rows then below is the code
add new button and a div where you will add new rows
<div id="divBar"></div>
<button type="button" onclick="AddnewRow()">Add new Row</button>
declare the jquery method
<script>
var i=0;
function AddnewRow()
{
var string = '<input type="text" name="BarList[' + i + '].Name" /><br/>';
$('#divBar').append(string);
i = i + 1;
}
</script>
Complete Page after doing this
<script src="~/scripts/jquery-1.10.2.min.js"></script>
@using (Html.BeginForm("Index", "Default", FormMethod.Post))
{
<span> Name:</span>
@Html.TextBoxFor(m => m.Name)
<span> List of Bars</span>
<div id="divBar"></div>
<button type="button" onclick="AddnewRow()">Add new Row</button>
<input type="submit" value="save" />
}
<script>
var i=0;
function AddnewRow()
{
var string = '<input type="text" name="BarList[' + i + '].Name" /><br/>';
$('#divBar').append(string);
i = i + 1;
}