2

I followed an online tutorial to dynamically add items to a bound list model using ajax, which works perfectly. (http://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/comment-page-2/#comment-68909)

My question is, how would I correctly remove items from the list? Right now what I have done is add a delete link which when clicked removes the item from the view. However, when I submit the form I noticed that the modelState is no longer valid and it has null entries for the item that was removed from the view. So I guess the model is not being updated.

Test.cshtml

@model TesterManager.Models.Test

<div class="form-group">
    @Html.LabelFor(model => model.Software, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-group">
            <div class="col-md-5">
                @Html.DropDownListFor(m => m.Software, TesterManager.Models.Helper.GetTestSoftwares(), "Choose a USB Card", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Software, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-5">
                @Html.EditorFor(model => model.Version, new { htmlAttributes = new { @class = "form-control", @title = "Enter a USB FW Version", @placeholder = "Enter a USB FW Version" } })
                @Html.ValidationMessageFor(model => model.Version, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-2">
                <a href="#" id="remove-test" onclick="$(this).parent().parent().parent().parent().remove();">Delete</a>
            </div>
        </div>
    </div>
</div>

AdminTesterConfigurations.cshtml (snippet):

@model TesterManager.Models.AdminTesterConfigurations

<div class="form-group">
    <div class="col-md-6">
        ....
    </div>
</div>
<hr />
<div class="form-group">
    <div class="col-md-12">
        <h3>Test Software</h3>
        <div id="test-list">
            @Html.EditorForMany(x => x.Tests, x => x.Index)
        </div>
        <input type="button" id="add-test" value="Add" />
    </div>
</div>

RequestEditViewModel.cshtml:

@model TesterManager.Models.RequestEditViewModel

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })    
    @Html.EditorFor(model => model.ShippingLocation)
    @Html.EditorFor(model => model.RequesterTesterConfigurations)


    @Html.EditorFor(model => model.AdminTesterConfigurations)                       

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>

Edit.cshtml:

@model TesterManager.Models.RequestEditViewModel

@Styles.Render("~/Content/Edit")

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Scripts
{
    <script>
        jQuery(document).ready(function ($) {
            $('#add-test').on('click', function ()  {
                jQuery.get('/TesterManager/Request/AddTest').done(function (html) {
                    $('#test-list').append(html);
                });
            });
        });
    </script>
}


@using (Html.BeginForm())
{
    <h2>Edit</h2>

    @Html.AntiForgeryToken()
    @Html.EditorFor(x => x);
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

RequestController.cs

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(RequestEditViewModel request)
    {
        if (ModelState.IsValid)
        {
            Request domainRequest = new Request(request);
            requests.Add(domainRequest);
            return RedirectToAction("Index");
        }
        return View(request);
    }

    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public ActionResult AddTest()
    {
        var request = new RequestEditViewModel();
        request.AdminTesterConfigurations.Tests.Add(new Test());

        return View(request);
    }
AndeeC
  • 397
  • 1
  • 6
  • 16
  • Refer the answers [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) - you need the hidden input for the collection indexer. –  May 04 '16 at 21:56
  • I'm using an extension that is used in the tutorial I referenced. I can do @Html.EditorForMany(x => x.Tests, x => x.Index) Which adds the hidden input with the index. Let me know if I'm misunderstanding you – AndeeC May 04 '16 at 23:13
  • If that extension method works correctly, then what is your problem? I can only assume it does not work, in which case use the `BeginCollectionItem()` HtmlHelper (refer 2nd link) or the client side template option if you want best performance. –  May 04 '16 at 23:19
  • I realized that the problem was that when I would remove the item from the list in the view, I was not removing the hidden input as well. I updated the code to remove the hidden input and it works fine now. I will take your approaches into consideration for better performance. Thanks. – AndeeC May 04 '16 at 23:31

1 Answers1

1

I realized that the problem was that when I would remove the item from the list in the view, I was not removing the hidden input for the collection indexer as well. I updated the code to remove the hidden input and it works fine now.

AndeeC
  • 397
  • 1
  • 6
  • 16