将C#模型转换为纯json-string [英] Convert C# model to plain json-string

查看:473
本文介绍了将C#模型转换为纯json-string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有简单的方法可以将C#对象转换为可以转义并可以被javascript使用的纯字符串?

Is there any simple way to convert an C#-object into a plain string that is escaped and can be used by javascript?

我尝试将字符串传递给jQuery函数,该函数将用真实值替换此字符串的某些部分,以通过$.ajax将它们作为请求对象传递.

I try to pass the string into a jQuery-function which will replace some parts of this string with real values to pass them as request-object via $.ajax.

无论我尝试了什么(在互联网上找到),都无法正常工作.

Whatever I tried (found in the internet) doesn't work.

目前,我有:

var jsVariable = "@Html.Raw(Json.Encode(new MyClass()))"

但这会抛出Uncaught SyntaxError: Unexpected identifier,因为"不能正确转义.

but this throws an Uncaught SyntaxError: Unexpected identifier as of the " are not escaped correctly.

更新1

最后,我想像这样的JSON字符串

At the end I would like to have the JSON-string like

"{"Prop1": "{0}", "Prop2":"{1}"}"

我可以(在javascript中)致电

var request = string.Format(jsVariable, value1, value2);

启用

$.ajax({
    type: "POST",
    url: "someUrl",
    data: $.parseJson(request),
    success: function(data) {
        console.log("success");
    },
    dataType: "JSON"
})

推荐答案

只需删除双引号即可.

确保将其添加到视图的脚本标签中.

Make sure this is added in the script tag of your view.

var jsVariable = @Html.Raw(Json.Encode(new MyClass()))

然后,您将获得一个具有其属性的javascript对象-只要定义了MyClass并且可以在CSHTML中对其进行访问即可.

you'd then get a javascript object with its properties - provided MyClass is defined, and is accessible in your CSHTML.

jsVariable.myProp, jsVariable.myOtherProp. .等等

这篇关于将C#模型转换为纯json-string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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