将模型分配给 Razor 中的 Javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13419676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning the Model to a Javascript variable in Razor
提问by Seriphos
I have a strongly-typed view bound to an object which contains a Collection (list) of some objects. I know Razor gets executed on the server-side when it's generating the page, whereas Javascript variables don't get instantiated until after the page is displayed... but would it somehow be possible to convert the Model (that the view is bound to) or any of its fields to JSON in Razor without resorting to an AJAX call to fetch that data afterwards?
我有一个强类型视图绑定到一个对象,该对象包含一些对象的集合(列表)。我知道 Razor 在生成页面时在服务器端执行,而 Javascript 变量直到页面显示后才被实例化......但是是否可以以某种方式转换模型(视图绑定到) 或其任何字段在 Razor 中转换为 JSON,而无需借助 AJAX 调用来获取该数据?
You know, something like...
你知道,像...
var myJavascriptVariable = @Model.MyCollection
where @Model.MyCollection
is a list of some objects.
哪里@Model.MyCollection
是一些对象的列表。
Thanks
谢谢
回答by Artem Vyshniakov
To get json data you can use the following construction:
要获取 json 数据,您可以使用以下结构:
var jsData = @Html.Raw(Json.Encode(Model.MyCollection));
回答by andres descalzo
Try this, with this you can have the unobtrusive javascript:
试试这个,这样你就可以拥有不显眼的 javascript:
HTML (Razor):
HTML(剃刀):
<script id="data" type="text/data-template">
@Html.Raw(Json.Encode(Model.MyCollection))
</script>
JS (you can user this in external file):
JS(您可以在外部文件中使用它):
var
jsonString = $('#data').html(),
jsonValue = (new Function( "return( " + jsonString + " );" ))();
HTML:
HTML:
<script id="data" type="text/data-template">
{ 'name': 'Pedro', 'Age': 33}
</script>
<div id="result"></div>
JS?
JS?
var
jsonString = $('#data').html(),
jsonValue = (new Function( "return( " + jsonString + " );" ))();
$('#result').html(jsonValue.name);
?
?