You should use jQuery to dynamically create a row with all the 3 input fields when user clicks on the Add button.
So in your razor view (ex:Create), create the first row with the three form fields.
@using (Html.BeginForm())
{
<a href="#" id="addRow">Add</a>
<div id="items">
<div class="itemRow">
<label>Name</label> <input type="text" class="formfield" name="Name" />
<label>Age</label> <input type="text" class="formfield" name="Age" />
<label>CreateDate</label><input type="text" class="formfield" name="CreateDate" />
</div>
</div>
<input type="submit" id="btnSubmit" />
}
Now we will add some client side code to listen to the click
event on the Add link, create a clone of the container div(with css class itemRow
) and append it to the outer container div(with id items
). When user clicks the submit button, we will read the form fields and build an array of object and post that to the server using jQuery ajax.
@section Scripts
{
<script type="text/javascript">
$(function () {
$("#addRow").click(function (e) {
e.preventDefault();
var template = $("#items").find(".itemRow").first();
var newRow = template.clone();
newRow.find("input.formfield").val("");
$("#items").append(newRow);
});
$("#btnSubmit").click(function (e) {
e.preventDefault();
var _this = $(this);
var url =_this.closest("form").attr("action");
var rows = [];
var items = $(".itemRow");
$.each(items, function (i, item) {
var name = $(item).find("input[name='Name']").val();
var age = $(item).find("input[name='Age']").val();
var createDt = $(item).find("input[name='CreateDate']").val();
var row = { Name: name, Age: age, CreateDate: createDt };
rows.push(row);
});
//Let's post to server
$.ajax({
type:"POST",
url: url,
data: JSON.stringify(rows),
contentType: "application/json"
})
.done(function (result) {
//do something with the result
})
});
});
</script>
}
Now you need an HttpPost action method to handle your form posting.
[HttpPost]
public ActionResult Create(IEnumerable<CreateUser> model)
{
foreach(var item in model)
{
// to do :Save
}
return Json( new { status ="success"});
}
and your CreateUser
view model will look like
public class CreateUser
{
public string Name { set;get;}
public int Age { set; get; }
public DateTime CreateDate { set; get; }
}