5

I wanna do something like this:

[HttpPost]
public ActionResult Index(Foo foo)
{
    foo.Name = "modified";

    return View(foo);
}

but when my view is rendered, it always has the old values! How can I modify and return? Must I clear the ModelState everytime?


My view:

@model MvcApplication1.Models.Foo


@using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Name)
    @Html.TextBoxFor(m => m.Description)

    <input type="submit" value="Send" />
}
MuriloKunze
  • 15,195
  • 17
  • 54
  • 82

2 Answers2

4

I think this might be expected behavior because the "normal" scenario where you send back the same model to the view is when the model has errors.

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

stephen.vakil
  • 3,492
  • 1
  • 18
  • 23
1

MVC uses ModelState on postback to populate the View, not the passed model. To update a single field before returning to the view try something like this:

var newVal = new ValueProviderResult("updated value", "updated value", CultureInfo.InvariantCulture);
ModelState.SetModelValue("MyFieldName", newVal);

More info here: ModelStateDictionary.SetModelValue()

Ryan Russon
  • 1,051
  • 9
  • 16
  • Microsoft's documentation is dense at the best of times but the stuff on [ValueProviderResult](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.valueproviderresult?view=aspnetcore-1.0) is inpenetrable! All I wanted to do was set a boolean value in the model when returning it following a failed POST. Got there in the end but it was painful! – Philip Stratford Oct 02 '20 at 15:09