Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a modified viewModel to view

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" />
}
like image 648
MuriloKunze Avatar asked Jun 06 '12 19:06

MuriloKunze


2 Answers

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

like image 162
stephen.vakil Avatar answered Nov 03 '22 15:11

stephen.vakil


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()

like image 1
Ryan Russon Avatar answered Nov 03 '22 16:11

Ryan Russon