MVC JsonResult的用法
本文导读:当客户端调用某个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;
![](http://www.studyofnet.com/Codefan-Controls/OutliningIndicators/None.gif)
![](http://www.studyofnet.com/Codefan-Controls/OutliningIndicators/None.gif)
namespace Mvc1.Controllers
![](http://www.studyofnet.com/Codefan-Controls/OutliningIndicators/ExpandedBlockStart.gif)
{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; }
}
}
}
转自:http://www.studyofnet.com/news/594.html