2013-04-04 62 views
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;}"); 

謝謝!

回答