如何传递在服务器端生成的json字符串,并将其用作MVC中客户端javascript中的参数

时间:2017-06-30 18:38:13

标签: javascript json asp.net-mvc datatables

大家好,这将是我的第一个问题!

所以基本上我想将序列化数组从服务器端传递到客户端,然后将其用作JS中的参数。现在我通过viewModel将它作为常规字符串发送并尝试使用@ Html.Raw()注入它,但是它不起作用:

        var table = $('#shipments').dataTable({
            "bServerSide": true,
            "sAjaxSource": "GetShipmentsAH",
            "bProcessing": true,
            "bJQueryUI": true,
            "fnCreatedRow": function (nRow, aData, iDataIndex) {
                $(nRow).attr('shipID', aData[0]);
            },
            "aoColumns": @Html.Raw(Model.ShipmentsAoColJSon);
        });

这是Model.ShipmentsAoColJSon的值:

  

[{" SNAME":" ID"" sDefaultContent":""" bSortable&#34 ;:真," bSearchable":真," SSEARCH":""},{" SNAME":" EAN" " sDefaultContent":""" bSortable":真," bSearchable":真," SSEARCH&#34 ;: ""},{" SNAME":"串行"" sDefaultContent":""&#34 ; bSortable":真," bSearchable":真," SSEARCH":""},{" SNAME":&# 34; N T个#34;" sDefaultContent":""" bSortable":真," bSearchable":真,&#34 ; SSEARCH":""},{" SNAME":" StoreUnitNr"" sDefaultContent":"&# 34;," bSortable":真," bSearchable":真," SSEARCH":""},{" SNAME& #34;:" FCODE"" sDefaultContent":""" bSortable":真," bSearchable" :真," SSEARCH":""},{" SNAME":" ProdDesc"" sDefaultContent&#34 ;: """ bSortab乐":真," bSearchable":真," SSEARCH":""}]

当我只是复制粘贴它直接代码它工作正常。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我找到了问题的根源。当我将其复制粘贴到它工作的html标签时,脚本存储在外部.js文件中。似乎@Html razor只能在主html页面上使用,但在js文件中不能使用。要处理我在我的Html中写的这个:

var ShipAoColJSon = @ Html.Raw(Model.ShipAoColJSon);

然后传递给js。文件:

var table = $('#shipments').dataTable({
    "bServerSide": true,
    "sAjaxSource": "GetShipmentsAH",
    "bProcessing": true,
    "bJQueryUI": true,
    "fnCreatedRow": function (nRow, aData, iDataIndex) {
        $(nRow).attr('shipID', aData[0]);
    },
    "aoColumns": ShipAoColJSon
});