Home > Backend Development > C++ > How Can I Access MVC Model Properties Using JavaScript?

How Can I Access MVC Model Properties Using JavaScript?

Susan Sarandon
Release: 2025-01-10 20:14:46
Original
374 people have browsed it

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:

var floorplanSettings = "@Model.FloorPlanSettings";
alert(floorplanSettings.IconsDirectory);
Copy after login

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));
Copy after login

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));
Copy after login

You can now access properties using serialized JavaScript objects:

alert(floorplanSettings.IconsDirectory);  // 访问IconsDirectory属性
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template