Asp.Net MVC 自定义一个ActionResult用于AJAX交互
1、在使用JQ做AJAX交互时我们通常需要做如下判断:
1、http请求本身是否成功;
2、我们的方法执行是否成功;
3、如果失败了,是什么原因;
一般写法是这样:
var url = "http://locahost/xxxx“ $.ajax({ type: "POST", url: url, data: null, dataType: "json", success: function (res) { if (res.success == true) { //// after success } else { /// unsuccess
alert(res.msg); } }, error: function () { /// http error alert("发生错误,请刷新重试!"); } });
2、所以我们在程序中有很多地方需要返回类似这样的JSON数据:
{ "success": true, "code": 200 }
{ "success": false, "code": 500 , "msg":"用户名密码错误!" }
3、我们定义一个ActionResult来方便每一次返回一样格式的数据,提高编码效率同时也提高一致性,减少疏忽导致的错误;
JObjectActionResult:
using System; using System.Text; using System.Web; using Newtonsoft.Json.Linq; using System.Web.Mvc; public class JObjectActionResult : ActionResult { public JObject JObject { get; set; } public Encoding ContentEncoding { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; response.ContentType = "application/json"; if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (JObject != null) { response.Write(JObject.ToString()); } } }
再使用附加方法附加到Controller上;
JObjectActionResultExtensions
public static class JObjectActionResultExtensions { public static JObjectActionResult JObjectResult(this Controller controller, JObject obj) { return new JObjectActionResult { JObject = obj }; } public static JObjectActionResult JObjectResult(this Controller controller, bool success) { JObject obj = new JObject(); obj.Add("success", success); if (success) { obj.Add("code", 200); obj.Add("msg", "Success!"); } else { obj.Add("code", 500); obj.Add("msg", "Error!"); } return JObjectResult(controller, obj); } public static JObjectActionResult JObjectResult(this Controller controller, bool success, int code, string msg) { JObject obj = new JObject(); obj.Add("success", success); obj.Add("code", code); obj.Add("msg", msg); return JObjectResult(controller, obj); } }
4、使用举例:
那么我们在Controller中使用的时候只需要一句代码就可以了:
[HttpPost] public ActionResult Delete(int id) { if (id <= 0) { return this.JObjectResult(false, 500, "Error ID"); } var command = new CustomerDeleteCommand(new int[] { id }); var result = CommandBus.Submit(command); if (!result.Success) { return this.JObjectResult(false, 510, result.Message); } return this.JObjectResult(true); }