使用MVC之后, 默認的ActionResult 有很多子類譬如 JsonResult之類, 可以很方便. 基本用法如下:
public ActionResult GetVacation()
{
var dt = ...(省略);
if (dt == null || dt.Rows.Count==0) return Json(new { success = false, msg = "相應空邏輯!" }); ;
return Json(new {
success = true,
...(省略)
});//省略內容
}
默認只能采用POST方式調用方法, Get 不行, 需要構建 JsonRequestBehavior 為AllowGet 方式. 返回 response.
public JsonResult W1ArchiveOTUpdate(string xxx1, string xxx2)
{
JsonResult response = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
var ret = Biz.XXX(Request.Cookies["XXX"].Value);
response.Data = new { success = ret.Success, msg = ret.Msg };
return response;
}
另一種情況, 返回數據行過多, 數據超過了默認限定, 記不清多少了, 所以采用了一個JsonResult 子類來定義到int.MAX. 如果還不行, 請考慮業務問題, 能分頁就分頁把.
過度方案:
public class LargeJsonResult : JsonResult
{
const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
public LargeJsonResult()
{
MaxJsonLength = int.MaxValue;//102400;
RecursionLimit = 100;
}
public new int MaxJsonLength { get; set; }
public new int RecursionLimit { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
response.Write(serializer.Serialize(Data));
}
}
}
//調用方式
public ActionResult XXXX(string XXX1, string XXX2)
{
var ret = Biz.XXX();
return new LargeJsonResult
{
Data = ret.Data
};
//return Json(ret);
}
參考:
