将 .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 \" "}");
谢谢你!