Start by creating a view model to represent what you want to edit. I assume cashAmount is a monetary value, so it should be decimal (add other validation and display attributes if necessary)
public class CashRecipientVM { public int? ID { get; set; } public decimal Amount { get; set; } [Required(ErrorMessage = "Please enter the name of the recipient")] public string Recipient { get; set; } }
Then create a partial view (say) of _Recipient.cshtml
@model CashRecipientVM <div class="recipient"> @using (Html.BeginCollectionItem("recipients")) { @Html.HiddenFor(m => m.ID, new { @class="id" }) @Html.LabelFor(m => m.Recipient) @Html.TextBoxFor(m => m.Recipient) @Html.ValidationMesssageFor(m => m.Recipient) @Html.LabelFor(m => m.Amount) @Html.TextBoxFor(m => m.Amount) @Html.ValidationMesssageFor(m => m.Amount) <button type="button" class="delete">Delete</button> } </div>
and method of returning this partial
public PartialViewResult Recipient() { return PartialView("_Recipient", new CashRecipientVM()); }
Then your main get method will be
public ActionResult Create() { List<CashRecipientVM> model = new List<CashRecipientVM>(); ....
and his presentation will be
@model IEnumerable<CashRecipientVM> @using (Html.BeginForm()) { <div id="recipients"> foreach(var recipient in Model) { @Html.Partial("_Recipient", recipient) } </div> <button id="add" type="button">Add</button> <input type="submit" value="Save" /> }
and will include a script to add html for the new CashRecipientVM
var url = '@Url.Action("Recipient")'; var form = $('form'); var recipients = $('#recipients'); $('#add').click(function() { $.get(url, function(response) { recipients.append(response);
and script to delete an item
$('.delete').click(function() { var container = $(this).closest('.recipient'); var id = container.find('.id').val(); if (id) {
And the form will return back to
public ActionResult Create(IEnumerable<CashRecipientVM> recipients)