"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Accessing MVC model attribute method using JavaScript

Accessing MVC model attribute method using JavaScript

Posted on 2025-04-29
Browse:254

How Can I Access MVC Model Properties Using JavaScript?

Access MVC model properties in JavaScript

Question: How to access data bound to a view model in JavaScript code? For example, how to access the properties of FloorPlanSettingsModel in JavaScript?

Initial attempt:

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. The method is as follows:

Serialize the entire model:

var model = @Html.Raw(Json.Encode(Model));

Serialize specific model attributes:

]

If you only need a specific property, such as FloorPlanSettings, just encode that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

Now you can access properties using serialized JavaScript objects:

alert(floorplanSettings.IconsDirectory);  // 访问IconsDirectory属性
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3