本文導讀:當用戶端調用某個Action方法并希望以JSON的格式傳回請求的資料時,ASP.NET MVC需要有一種機制将CLR對象轉換成JSON格式予以響應,而這可以通過JsonResult來解決。下面介紹MVC中JsonResult的用法
一、MVC中JsonResult定義的代碼片段
public class JsonResult : ActionResult
{
public override void ExecuteResult(ControllerContext context);
public object Data { get; set; }
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public JsonRequestBehavior JsonRequestBehavior { get; set; }
public int? MaxJsonLength { get; set; }
public int? RecursionLimit { get; set; }
}
public enum JsonRequestBehavior
{
AllowGet,
DenyGet
}
其中:JsonResult具有一個object類型的屬性Data表示需要被轉換成JSON格式的資料對象。屬性ContentEncoding和ContentType表示為目前響應設定的編碼方式和媒體類型,預設采用的媒體類型為“application/json”。
備注:
出于對安全的考慮,JsonResult在預設的情況下不能作為對HTTP-GET請求的響應,在這種情況下并會直接抛出一個InvalidOperationException異常。我們可以通過它的JsonRequestBehavior屬性開啟JsonResult對HTTP-GET請求的支援。該屬性類型為JsonRequestBehavior枚舉,兩個枚舉項AllowGet和DenyGet分别表示允許/拒絕支援對HTTP-GET請求的響應。JsonResult的JsonRequestBehavior屬性在初始化的時候被設定為DenyGet,如果我們需要用建立的JsonResult來響應HTTP-GET請求,需要顯式地将它的JsonRequestBehavior屬性設定為AllowGet。
二、Controller中傳回JsonResult的方法
在抽象類Controller同樣定義如下一系列的Json方法用于根據指定的資料對象、編碼方式以及JsonRequestBehavior來創相應的JsonResult。
public abstract class Controller : ControllerBase,...
{
//其他成員
protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);
protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior);
}
三、MVC JsonResult的執行個體
1、視圖頁面
<!DOCTYPE html>

<html>
<head runat="server">
<title>Index2</title>
<script src="/Scripts/jquery-1.4.4。js" type="text/javascript"></script>
<script type="text/javascript">
var login = function () {
var data = { "username": $.trim($("#username").val()), "pwd": $.trim($("#pwd").val()) }
// $.post("/Home/Login", data, function (message) {
// if (message.success) {
// alert(message.msg);
// }
// else {
// alert(message.msg);
// }
// }, "json");
$.ajax({ type: "post", url: "/Home/Login", data: data, success: function (message) {
if (message.Success) {
alert(message.Msg);
}
else {
alert(message.Msg);
}
}, dataType: "json"
});
}
</script>
</head>
<body>
<div id="nav">
<a href="/Home/Index">ajax+Handler</a> <a>ajax+action</a>
</div>
<div>
<h3>
Login</h3>
Username:<input id="username" name="username" type="text" /><br />
Userpass:<input id="pwd" name="pwd" type="password" /><br />
<button type="button" onclick="login()">
Submit</button>
</div>
</body>
</html>
2、控制器
using System.Web.Mvc;
namespace Mvc1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
//
// GET: /Home/Index2
public ActionResult Index2()
{
return View();
}
// Post: /Home/Login
[HttpPost]
public JsonResult Login()
{
string username=Request["username"];
string pwd = Request["pwd"];
message msg = null;
if (username == "rain" && pwd == "m123")
{
msg = new message(true, "Success");
}
else
{
msg = new message(false, "Fail");
}
return Json(msg);
}
}
class message
{
bool success;
string msg;
public message(bool success, string msg)
{
this.success = success;
this.msg = msg;
}
public bool Success
{
get { return success; }
set { success = value; }
}
public string Msg
{
get { return msg; }
set { msg = value; }
}
}
}