Home >Backend Development >C++ >How Can I Access MVC Model Properties Using JavaScript?
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:
<code class="language-javascript">var floorplanSettings = "@Model.FloorPlanSettings"; alert(floorplanSettings.IconsDirectory);</code>
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:
<code class="language-javascript">var model = @Html.Raw(Json.Encode(Model));</code>
Serialize specific model properties:
If you only need a specific attribute, such as FloorPlanSettings, just encode the attribute:
<code class="language-javascript">var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));</code>
You can now access properties using serialized JavaScript objects:
<code class="language-javascript">alert(floorplanSettings.IconsDirectory); // 访问IconsDirectory属性</code>
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!