从 Javascript 访问 MVC 的模型属性 [英] Accessing MVC's model property from Javascript

查看:28
本文介绍了从 Javascript 访问 MVC 的模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型,它包含在我的视图模型中

I have the following model which is wrapped in my view model

public class FloorPlanSettingsModel
{
    public int Id { get; set; }
    public int? MainFloorPlanId { get; set; }
    public string ImageDirectory { get; set; }
    public string ThumbnailDirectory { get; set; }
    public string IconsDirectory { get; set; }
}

如何从 Javascript 访问上述属性之一?

How do I access one of the above properties from Javascript?

我试过了,但我得到了未定义"

I tried this, but I got "undefined"

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

推荐答案

您可以通过执行以下操作将整个服务器端模型转换为 Javascript 对象:

You could take your entire server-side model and turn it into a Javascript object by doing the following:

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

在您的情况下,如果您只想要 FloorPlanSettings 对象,只需传递该属性的 Encode 方法:

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

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

这篇关于从 Javascript 访问 MVC 的模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆