Search code examples
c#asp.net-mvc-4razor-2

Why does mvc "remember" old model within "beginform"?


I found some seriously weird behavior in MVC when I redisplay a form multiple times. I was wondering if anyone could help me clear up whats going on:

My controller code:

   [HttpPost, ActionName("Delete")]
    public ActionResult Delete(Person person)
    {
        if (person.PersonID != default(int))
        {
            try
            {
                _personRepository.Delete(person.PersonID);
                _personRepository.Save();
            }
            catch (Exception)
            {
            }
        }

        return PartialView(new Person() {Name = Lang("Personen er slettet")});
    }

My view code:

@model Person
<h3>@Html.Lang("Er du sikker på at du vil slette")?</h3>
<div>@Html.DisplayNameFor(m => m.Name): "@Model.Name"</div>
<div>@Html.DisplayNameFor(m => m.PersonID): "@Model.PersonID"</div>
@{
    var id = Model.PersonID;
}
@using (Html.BeginForm())
{
    <p>
        @Html.HiddenFor(m => Model.PersonID)
        @Html.HiddenFor(m => Model.Name)
        <input type="hidden" value="@Model.PersonID" id="personID" name="personID"/>
        <input type="hidden" value="@Model.Name" id="Name" name="Name"/>
    </p>
}

The result I get when Delete(Person person) function returns the view:

<h3>Er du sikker p&#229; at du vil slette?</h3>
<div>Navn: "Personen er slettet"</div>
<div>PersonID: "0"</div>

<form action="/KongsbergGruppenCompanyRegister/Person/Delete?PersonID=10" method="post">    <p>
        <input data-val="true" data-val-required="The PersonID field is required." id="PersonID" name="PersonID" type="hidden" value="10" />
        <input data-val="true" data-val-length="The field Navn must be a string with a maximum length of 255." data-val-length-max="255" id="Name" name="Name" type="hidden" value="dfhgdfgh" />
        <input type="hidden" value="0" id="personID" name="personID"/>
        <input type="hidden" value="Personen er slettet" id="Name" name="Name"/>
    </p>
</form> 

Let me point out the where suddenly the model is the "pre deleted" model. How and why is this happening, and what would be a more correct way to code this? ( I can get it to work by simply not using the "hiddenFor" methods, but that seems counter intuitive)


Solution

  • CodeCaster has it right in that it's almost a duplicate, however the answer from the other thread is not the correct one. I found the correct answer in one of the comments in the other thread:

    http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

    The correct answer is that the MVC helpers read the values directly from the request. They do this to be able to properly display erroneous submitted information (like "dog" in an int field).

    The other thread suggested using "ModelState.Clear()", I found however that this did not work. The workaround I used that worked perfectly was using "RedirectToAction".