Michel Fornaris
Michel Fornaris

Reputation: 372

Model values no shown updated in the view after a POST

I have the following simple (for the purpose of the question) controller/action:

public ActionResult Edit(int id)
{
    User user = repository.GetUser(id);
    return View(user);
}

[HttpPost]
public ActionResult Edit(User user) 
{
    user.Name = user.Name.ToUpper();
    return View(user);
}

and the view was generated as Edit for User using regular steps in VS

The problem I'm facing is that whatever has been entered in the Name text-box will be showed back to the user but without uppercase. I have checked and the Edit action for POST is executed and user.Name value become UPPER CASE but .TextBoxFor is still using the value entered by the user which is in lower case.

I have checked also that if I print (without the use of any Html Helper) the value of Model.Name after the POST, it will be in UPPER CASE as I would like the Html.TextBoxFor to behave.

Is that a bug of MVC?

Is there a way of making this work in the way I want, meaning that the action/controller is the piece in the puzzle to decide data values for the View and not the view using the ones in the Request object and ignoring the changes that the controller might have done?

Thanks in advance

Upvotes: 2

Views: 1157

Answers (2)

Jeferson Tenorio
Jeferson Tenorio

Reputation: 2180

You can use ModelState.Remove(nameOfProperty) like:

[HttpPost]
public ActionResult Edit(User user) 
{
    ModelState.Remove("Name");
    user.Name = user.Name.ToUpper();
    return View(user);
}

It's will work.

Upvotes: 0

wnascimento
wnascimento

Reputation: 1959

Use RedirectToAction and pass the Id for the user, it's not a bug, is the POST Behaviour

Update: You need to persist the information before RedirectToAction as Dismissile said, or use TempData if you do not want to persist.

[HttpPost]
public ActionResult Edit(User user) 
{
    user.Name = user.Name.ToUpper();
    return RedirectToAction("Edit", new { id = user.id });
}

Upvotes: 1

Related Questions