使用 Html.Raw 将 ASP.NET 模型序列化为 JSON 的 Razor 语法错误 [英] Razor syntax error serializing ASP.NET Model to JSON with Html.Raw

查看:19
本文介绍了使用 Html.Raw 将 ASP.NET 模型序列化为 JSON 的 Razor 语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一行在 Visual Studio 2012 中给了我一个语法错误(字面意思就是语法错误"):

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 在这种情况下是在我的 cshtml 顶部声明的 @model MyApp.ViewModels.MyViewModel 的实例.

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?

根据要求,提供更多背景信息.这是整个 $(document).ready():

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>

推荐答案

使用函数

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

Using function

Implement a simple JavaScript set function that returns input argument:

function set(value){
    return value;
}

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

Use this function to assign Razor model value to a JavaScript variable:

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

<小时>

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


As an option you can use self-calling function:

var data = function() { return set(@Json.Encode(Model)); }();

这篇关于使用 Html.Raw 将 ASP.NET 模型序列化为 JSON 的 Razor 语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆