PseudoPsyche
PseudoPsyche

Reputation: 4582

Different value displaying in Razor textbox than is in model

I'm having an issue where a value I set in the model is incorrect when accessing it from the Razor code. If I place a breakpoint on the if statement below and inspect Model.TestVal, it contains the correct value. However, that value is not what is displayed in the generated text box, and I can't figure out why the two are different.

    @if (Model.IsValid)
    {
        <div class="testRow">
            <label class="testLabel" for="TestVal">Test Value:</label>
            <div class="testField" id="TestVal">@Html.TextBoxFor(m => m.TestVal, ViewHelper.IsEditable("TestVal"))</div>
        </div>
    }

Upvotes: 0

Views: 312

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The TextBoxFor helper will first look at the value in the ModelState and after that the value in your model. It's a common gotcha when people try to change some model property value in a POST action:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    model.SomeProperty = "some new value";
    return View(model);
}

In this case the new value will not be taken into account because the ModelState already contains the originally POSTed value and that's what will be displayed by the TextBoxFor helper. To make this work you will also need to remove the original value from the model state:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    ModelState.Remove("SomeProperty");
    model.SomeProperty = "some new value";
    return View(model);
}

or completely wipe it out:

ModelState.Clear();

Upvotes: 3

Related Questions