简体   繁体   中英

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. 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?

You know, something like...

var myJavascriptVariable = @Model.MyCollection

where @Model.MyCollection is a list of some objects.

Thanks

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

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

Try this, with this you can have the unobtrusive javascript:

HTML (Razor):

<script id="data" type="text/data-template">
@Html.Raw(Json.Encode(Model.MyCollection))
</script>

JS (you can user this in external file):

var
   jsonString = $('#data').html(),
   jsonValue = (new Function( "return( " + jsonString + " );" ))();

Example

HTML:

<script id="data" type="text/data-template">
    { 'name': 'Pedro', 'Age': 33}
</script>
<div id="result"></div>

JS​

var
   jsonString = $('#data').html(),
    jsonValue = (new Function( "return( " + jsonString + " );" ))();

$('#result').html(jsonValue.name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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