0

I came across a problem with ambient form data, which I've tried to isolate into the following example.

View model:

public class ViewModel
{
    public int Value { get; set; }
}

Controller:

public class TestController
{
    public ViewResult Test1()
    {
        return(View(new ViewModel {Value = 1}));
    }

    [HttpPost]
    public ViewResult Test2(ViewModel vm)
    {
        vm.Value = 2;
        return(View(vm));
    }
}

Test 1 view:

@model ViewModel
@using(Html.BeginForm("Test2", "Test"))
{
    @Html.TextBoxFor(m => m.Value)
    <button type="submit">Send</button>
}

Test 2 view:

@model ViewModel
@Model.Value
@Html.TextBoxFor(m => m.Value)

Submitting the form in view 1 gives the, at least to me, surprising result in view 2: enter image description here

Seems like the posted value gets used in the TextBoxFor(). Anyone knows what's going on here and how to avoid it?

Robert
  • 485
  • 2
  • 6
  • 12
  • possible duplicate of [MVC 3 - Html.EditorFor seems to cache old values after $.ajax call](http://stackoverflow.com/questions/7414351/mvc-3-html-editorfor-seems-to-cache-old-values-after-ajax-call) – CodeCaster Apr 01 '15 at 10:53
  • Its because html helpers use ModelState values, not model values. When you post the model, its values are added to `ModelState` (along with any associated errors). Setting `vm.Value = 2;` has no effect unless you first call `ModelState.Clear();`. An explanation for the behavior is included in [this answer](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) –  Apr 01 '15 at 10:54
  • Or one of the many results for "asp.net mvc showing old posted model value". – CodeCaster Apr 01 '15 at 10:54

0 Answers0