I am working with a ASP.NET MVC4 application. I have created a view model which contains menu items and I can switch languages in page by Resources file.
#region Properties
[Display(Name = "MenuText", ResourceType = typeof(App.App_Resources.Menu))]
public string menuText { get; set; }
public List<MenuItem> menuItems { get; set; }
#endregion
However, I want to get this resource string in my .cshtml file, then I try as following
@model App.Models.MenuViewModel
@Html.LabelFor(model => model.menuText) <- Success
@Html.DisplayForModel("menuText") <- Success
@Model.menuText <- Fail
I inserted a break point and found out that Model contains a property which name is menuText but value is null. And I checked that Html also contains a property Model and its menuText also is null.
However, menuItems has items since I assign objects in constructor.
- Why the menuText cannot be initialized and assigned value to it?
- Why I can succeed to show the resource string with first two but Model.menuText is null and fail to show anything? What is different between the models in @Html.XXX and @Model?
@Model.menuTextretrieves the raw string value stored within themenuTextproperty. Attributes are ignored.Using
LabelForcauses theDisplayattribute of the property to be examined. The localised string is stored in the attribute, not the property.Note that I think the Model object/class should not be used to store information for display (that’s what
ViewDatais for), but rather only for round-trip data that is sent from the client to the server.