Accessing MVC model properties in JavaScript
Question: How to access data bound to a view model in JavaScript code? For example, how do I access the properties of FloorPlanSettingsModel in JavaScript?
First try:
var floorplanSettings = "@Model.FloorPlanSettings"; alert(floorplanSettings.IconsDirectory);
Answer:
To access MVC model properties from JavaScript, the model needs to be serialized into a JavaScript object. Here’s how:
Serialize the entire model:
var model = @Html.Raw(Json.Encode(Model));
Serialize specific model properties:
If you only need a specific attribute, such as FloorPlanSettings, just encode the attribute:
var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));
You can now access properties using serialized JavaScript objects:
alert(floorplanSettings.IconsDirectory); // 访问IconsDirectory属性
The above is the detailed content of How Can I Access MVC Model Properties Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!