Search code examples
c#asp.net-mvcasp.net-mvc-4postmvc-editor-templates

MVC Collection Missing items on Post


I've recently run into some behaviour with MVC4 that I'm hoping to gain some perspective on. The behaviour in my actual project uses more complex objects, but I was able to replicate it with simple objects, which is what I'm using in this question. My situation is as follows:

  1. I have a View that uses a Collection of strings as its model.
  2. I'm calling "EditorFor" to display each string in the collection.
  3. In the controller, I am populating the model with 7 string items and passing it to the view.
  4. The view renders all 7 items.
  5. I'm using jquery to remove the 2nd item in the collection from the DOM.
  6. I click submit to post back.
  7. I check the contents of my posted back model and it only contains the first item in the list. I expected to have 6 items in the list (7 minute the one I removed from the DOM).

The code for the described situation is as follows:

View

@model ICollection<string>

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.EditorFor(x => x);
    <input id="btnSubmit" type="submit" value="Submit" />
}

Controller

[HttpGet]
public ActionResult Index()
{
     List<string> vm = new List<string>
     {
         "one",
         "two",
         "threE",
         "four",
         "five",
         "six",
         "seven"
     };

     return View(vm);
}

[HttpPost]
public ActionResult Index(List<string> vm)
{
    return View(vm);
}

Thanks to anyone who helps out with this. Looking forward to increasing my understanding of MVC!


Solution

  • Possible duplicate of Strange behaviour in ASP.NET MVC: removing item from a list in a nested structure always removes the last item

    When removing items from a list on a postback, I don't need validation, so I use

    ModelState.Clear();
    

    anywhere during the round-trip back to the view, which solves my issue with this scenario.