2012-05-15 69 views
5

我還需要返回包含成功值(true或false)的JSON數據,它也需要結果消息。Asp.Net MVC3,返回成功JsonResult

所以我使用Dictionary來包含數據,但是當它返回到Jason數據時,它包含「」(Quot)。

JsonResult = new Dictionary<string, string>(); 
JsonResult.Add("Success", "False"); 
JsonResult.Add("Message", "Error Message"); 
return Json(JsonResult); 

返回,

{"Success":"False","Message":"Error Message"} 

但我需要,

{Success:False,Message:"Error Message"} //with out "" (Quot) 

任何人都知道這件事嗎?

謝謝!

回答

30
{"Success":"False","Message":"Error Message"} 

是有效的JSON。你可以檢查它here。在jsonlint.com

你甚至不需要一個字典來返回該JSON。您可以簡單地使用這樣的匿名變量:

public ActionResult YourActionMethodName() 
{ 
    var result=new { Success="False", Message="Error Message"}; 
    return Json(result, JsonRequestBehavior.AllowGet); 
} 

要從客戶端訪問此數據,您可以執行此操作。

$(function(){ 
    $.getJSON('YourController/YourActionMethodName', function(data) { 
     alert(data.Success); 
     alert(data.Message); 
    }); 
}); 
+0

+1我來寫這篇文章,雖然我不會用一個變量,但是這只是我的偏愛:) – mattytommo

+0

@mattytommo:我喜歡匿名類型在C#中的場景是這樣 – Shyju

+0

成功的關鍵還是必須用引號括起來,而你的代碼就是這樣做的。除非OP有錯字...他要求無效的JSON。您的代碼返回{「成功」:「假」,「消息」:「錯誤消息」} – BZink