0

This is my first question on stackoverflow, after many searches, but i still have a strange ASP MVC problem.

I have a View displayingList in a form containings inputs. I want allow the user to remove one or more element, by cheking it and apply on submit.

See the illustration of the problem here:
See the illustration of the problem here

The Model :

public class MTest
{
    public string Nom { get; set; }
    public bool Delete { get; set; }
}

The Controller :

public partial class TestController : Controller
{
    public virtual ActionResult Index()
    {
        List<MTest> m = new List<MTest>();

        m.Add(new MTest() { Nom = "A", Delete = false });
        m.Add(new MTest() { Nom = "B", Delete = false });
        m.Add(new MTest() { Nom = "C", Delete = false });
        m.Add(new MTest() { Nom = "D", Delete = false });

        return View(m);
    }

    [HttpPost]
    public virtual ActionResult Index(List<MTest> model)
    {
        model.RemoveAll(f => f.Delete == true);

        return View(model);
    }
}

The View :

@model List<MTest>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @for (int i = 0; i < Model.Count; i++)
    {
        @Html.EditorFor(model => model[i].Delete)
        @Html.EditorFor(model => model[i].Nom, new {
    }
    <input type="submit" value="Save" />
}

Currently, if i check the 'B' MTest element (for deleting it), i can see it disapear when i run step by step in the ActionResult Index(List model). But into the View : the result is not the same, and i don't understand why (see illustration).

Can somenone help me ?

Thanks a lot !

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Picsonald
  • 301
  • 3
  • 4

2 Answers2

0

Because of [HttpGet] of View Action Always Generate New FakeData. For Example if you have a Repository that read data from DB it Must work Correctly.

hamid_reza hobab
  • 925
  • 9
  • 21
0

According to the duplicate, the solution is to add ModelState.Clear(); before the return View(model); like this :

The controller :

[HttpPost]
public virtual ActionResult Index(List<MTest> model)
{
    model.RemoveAll(f => f.Delete == true);

    ModelState.Clear(); // You must add this row to clear cache
    return View(model);
}

Thanks for help and explanation !

Picsonald
  • 301
  • 3
  • 4