Assigning the Model to a Javascript variable in Razor

后端 未结 2 1807
南笙
南笙 2021-02-04 09:45

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,

相关标签:
2条回答
  • 2021-02-04 10:15

    To get json data you can use the following construction:

    var jsData = @Html.Raw(Json.Encode(Model.MyCollection));
    
    0 讨论(0)
  • 2021-02-04 10:21

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

    0 讨论(0)
提交回复
热议问题