25

This line is giving me a syntax error in Visual Studio 2012 (literally just 'Syntax Error'):

var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));

Model in this case is the instance of @model MyApp.ViewModels.MyViewModel declared at the top of my cshtml.

My model is serialized properly into the data var, and the application works correctly. Cosmetically it's just annoying to have the error permanently in my error list.

How should I modify the line so that the compiler is happy?

edit:

As requested, more context. Here's the entire $(document).ready():

<script type="text/javascript">

    $(document).ready(function () {

        $('#ReportDate').datepicker();
        $('#DispositionDate').datepicker();

        var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));

        var vm = new NonconformingProductViewModel(data);
        ko.applyBindingsWithValidation(vm);

        // validate on page load so all reqd fields are highlighted.
        var valid = ko.validation.group(vm, {deep: true});
        valid.showAllMessages(true);

    }); // end document.ready

</script>
4

5 回答 5

28

使用功能

实现一个set返回输入参数的简单 JavaScript 函数:

function set(value){
    return value;
}

使用此函数将 Razor 模型值分配给 JavaScript 变量:

var data = set(@Json.Encode(Model));

作为一个选项,您可以使用自调用功能:

var data = function() { return set(@Json.Encode(Model)); }();
于 2013-07-12T14:32:32.857 回答
17

尝试将其包装在 afunction中,如下所示:

var data = function() { return @Html.Raw(Json.Encode(Model)); }();
于 2013-07-14T20:44:22.743 回答
13

使用JSON.Net而不是 JavaScriptSerializer 或 DataContractJsonSerializer,以避免JSON Dates 的噩梦

var data = function () { 
    return @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)); }();
于 2014-07-26T16:57:47.910 回答
8

更简单!!这将解决这个小烦恼:

var model = [@Html.Raw(Json.Encode(Model))][0];

基本上智能感知想要周围的东西@Html.Raw。实际上并没有错,但我们必须处理智能感知的缺点。这里我们将结果声明为新数组的第一个索引,然后返回第一个索引。

仅供参考:如果您希望您的模型反映对 DOM 的更改,请尝试使用JSModel类。

于 2014-08-06T16:10:36.140 回答
4

您不需要编写任何新的 javascript 函数,只需将代码包装到括号中即可

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

在 Visual Studio 2015 中为我工作,不确定 VS2012

于 2016-03-06T16:40:13.660 回答