2

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?

atconway
  • 20,624
  • 30
  • 159
  • 229

3 Answers3

4

@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

Réda Mattar
  • 4,361
  • 1
  • 18
  • 19
3

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

Community
  • 1
  • 1
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
1

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>
WannaCSharp
  • 1,898
  • 2
  • 13
  • 19