将.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("{"Message":"let's try <b> this </b> and this \" "}");
谢谢!
答案 0 :(得分:6)
这是a small blog post about doing exactly this.
var someData = @Html.Raw(Json.Encode(yourViewModelCSharpObject))
您将实际对象传递给视图,而不是JSON字符串表示。
祝你好运!