通过JavaScript访问MVC的模型属性 [英] Accessing MVC's model property from Javascript
本文介绍了通过JavaScript访问MVC的模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的模型,它被包裹在我的视图模型
公共类FloorPlanSettingsModel
{
公众诠释标识{搞定;组; }
公众诠释? MainFloorPlanId {搞定;组; }
公共字符串ImageDirectory {搞定;组; }
公共字符串ThumbnailDirectory {搞定;组; }
公共字符串IconsDirectory {搞定;组; }
}
我如何访问上面的属性之一从Javascript?
我想这一点,但我得到了不确定
VAR floorplanSettings =@ Model.FloorPlanSettings
警报(floorplanSettings.IconsDirectory);
解决方案
您可以把你的整个服务器端模型,并通过执行以下操作把它变成一个JavaScript对象:
VAR模型= @ Html.Raw(Json.En code(型号));
在你的情况,如果你只是想FloorPlanSettings对象,只需通过恩code
方法属性:
VAR floorplanSettings = @ Html.Raw(Json.En code(Model.FloorPlanSettings));
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; }
}
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);
解决方案
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));
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屋!
查看全文