I am new to asp.net MVC. I have a dynamic table in my project. Adding dynamic rows in table is achieved with the help of following link
Adding and deleting rows in dynamic table in Asp.net mvc razor view
I need to edit and update the dynamic table. I have tried following code
My sample model
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
public class GiftViewModel
{
public string Age { get; set; }
public DateTime TheDate { get; set; }
public IEnumerable<Gift> Gifts { get; set; }
}
My sample Controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(GiftViewModel model)
{
// do work here
return RedirectToAction("Index");
}
public ViewResult AddNew()
{
return View("_TimeSheetView");
}
}
My sample Partial View
@model HelloWorldMvcApp.Gift
@using (Html.BeginCollectionItem("giftList"))
{
<div>
<span class="drop_medium">
@Html.TextBoxFor(m => m.Name)
</span>
<span class = "drop_medium">
@Html.TextBoxFor(m => m.Price)
</span>
</div>
}
My sample main view
@model HelloWorldMvcApp.GiftViewModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.Age)
@foreach (var data in Model.Gifts)
{
{ Html.RenderPartial("_TimeSheetView", data); }
}
@Html.ActionLink("Add another", "AddNew", null, new { id="addItem" })
<input type="submit" value="Save"/>
}
<script type="text/javascript">
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#dynamic").append(html); }
});
return false;
});
</script>
When I click 'Add Another' button a row is added to the table. After editing the values in the table When I click submit button I receive nothing in the controller. The IEnumerable Gifts variable is null. How to take the table values to the controller. Please help me to fix this is issue. Thanks in advance
Gifts
so its needs to beHtml.BeginCollectionItem("Gifts"))
(not"giftlist"
). And you have not shown the script that adds the new item. – user3559349<input name="Gifts[##].Name" ...> <input type="hidden" name="Gifts.Index" value="##" >
where##
is a Guid – user3559349