简体   繁体   English

将模型分配给Razor中的Javascript变量

[英]Assigning the Model to a Javascript variable in Razor

I have a strongly-typed view bound to an object which contains a Collection (list) of some objects. 我有一个强类型视图绑定到一个对象,该对象包含一些对象的Collection(列表)。 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 谢谢

要获取json数据,您可以使用以下构造:

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

Try this, with this you can have the unobtrusive javascript: 试试这个,你可以使用不引人注目的javascript:

HTML (Razor): HTML(Razor):

<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 + " );" ))();

Example

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM