2

将 .net 类序列化为 json 并在 javascript 中使用它的正确方法是什么?

例如在服务器端我们有这个:

    public ActionResult Index()
    {
        var someClass = new SomeClass { Message = "let's try <b> this </b> and this \" " };
        ViewBag.someDataJson = JsonConvert.SerializeObject(someClass);
        return View();
    }

    public class SomeClass
    {
        public string Message;
    }

在客户端:

<script type="text/javascript">
    $(document).ready(function() {
        var someData = $.parseJSON("@Html.Raw(ViewBag.someDataJson)");
        alert(someData.Message);
    });
</script>

将导致:

var someData = $.parseJSON("{"Message":"let's try <b> this </b> and this \" "}");

这是不正确的。同样没有 Html.Raw() 结果也将是不正确的:

var someData = $.parseJSON("{&quot;Message&quot;:&quot;let&#39;s try &lt;b&gt; this &lt;/b&gt; and this \&quot; &quot;}");

谢谢你!

4

1 回答 1

6

这是一篇关于如何做到这一点的小博客文章。

它用Json.Encode(someClass)

var someData = @Html.Raw(Json.Encode(yourViewModelCSharpObject))

您会将实际对象传递给视图,而不是 JSON 字符串表示。

祝你好运!

于 2013-04-04T21:49:42.827 回答