atconway
atconway

Reputation: 21314

Form Values from Model Not Updating in View After Post

I believe I'm missing something quite trivial here, but I'm not spotting it. I have a Post method, which modifies a Model property. I then want that model property to reflect the new property value. So here are the pieces:

Controller:

    [HttpPost]
    public ActionResult Index(HomeModel model)
    {

        ModelState.Clear(); //Didn't help
        model.MyValue = "Hello this is a different value";

        return View(model);

    }

Model:

public class HomeModel
{
    [Display(Name = "My Message")]
    public string MyValue { get; set; }

}

View:

@model MyApp.Models.HomeModel
@{
   ViewBag.Title = "My MVC App";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
   <div>
      @using (Html.BeginForm("Index", "Home"))
      {
         <h5>Hello</h5> 
         <input id="SendMessage" type="submit" value="Send Message"/> 
         @Html.LabelFor(m => m.MyValue)
      }

   </div>
</body>
</html>

When I debug the controller I can see the updated model, but my LabelFor always has the Display attribute as opposed to the value I provided of "Hello this is a different value". What am I missing here that this label is not updated?

Upvotes: 2

Views: 3301

Answers (3)

R&#233;da Mattar
R&#233;da Mattar

Reputation: 4381

@Html.LabelFor displays your property name (or the name defined in your DisplayAttribute), whereas @Html.DisplayFor displays your property content. If your want "Hello this is a different value" displays, replace @Html.LabelFor by @Html.DisplayFor

Upvotes: 4

Murali Murugesan
Murali Murugesan

Reputation: 22619

The html helper look at the ModelState when binding their values and then in the model.

So if you intend to modify any of the POSTed values inside your controller action make sure you remove them from the model state first:

 ModelState.Remove("PropertyName");

Read this MVC 3 - Html.EditorFor seems to cache old values after $.ajax call

Upvotes: 3

WannaCSharp
WannaCSharp

Reputation: 1898

That's the purpose of LabelFor, display the property name. Either use EditorFor or just access the model property directly inside a label tag it to your view

     <h5>Hello</h5> 
     <input id="SendMessage" type="submit" value="Send Message"/> 
     <label>@Model.MyValue</label>

Upvotes: 1

Related Questions