ASP.NET MVC ajax處理 AjaxResult


1、統一ASPNET MVC 對ajax請求響應格式定義,方便前端統一處理ajax結果.

  1)定義程序返回結果數據格式

 1 /// <summary>
 2     /// 執行結果
 3     /// </summary>
 4     /// <typeparam name="T"></typeparam>
 5     public class RunResult<T>
 6     {
 7         /// <summary>
 8         /// 操作狀態
 9         /// </summary>
10         public ResultStatus Status { get; set; }
11         /// <summary>
12         /// 操作異常
13         /// </summary>
14         public Exception Exception { get; set; }
15         /// <summary>
16         /// 數據結果
17         /// </summary>
18         public T Result { get; set; }
19         /// <summary>
20         /// 操作消息
21         /// </summary>
22         public string Message { get; set; }
23     }
View Code

  2)定義執行結果狀態

/// <summary>
    /// 執行結果
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RunResult<T>
    {
        /// <summary>
        /// 操作狀態
        /// </summary>
        public ResultStatus Status { get; set; }
        /// <summary>
        /// 操作異常
        /// </summary>
        public Exception Exception { get; set; }
        /// <summary>
        /// 數據結果
        /// </summary>
        public T Result { get; set; }
        /// <summary>
        /// 操作消息
        /// </summary>
        public string Message { get; set; }
    }
View Code

   3)返回前端數據格式

  public class AjaxEntity<T>
    {
        [JsonProperty(PropertyName = "Success")]
        public bool Success { get; set; }

        [JsonProperty(PropertyName = "Message")]
        public string Message { get; set; }

        [JsonProperty(PropertyName = "Data")]
        public T Data { get; set; }
    }
View Code

  4)定義asp.net mvc 中 ajax ActionResult

 public class AjaxResult<T> : CustomResult<AjaxEntity<T>>
    {
        private readonly RunResult<T> _runResult;

        public AjaxResult(RunResult<T> runResult)
        {
            _runResult = runResult;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override AjaxEntity<T> GetObject()
        {
            AjaxEntity<T> entity = new AjaxEntity<T> { Data = _runResult.Result };
            if (_runResult.Result is bool)
            {
                entity.Success = _runResult.Status == ResultStatus.Success && Convert.ToBoolean(_runResult.Result);
            }
            else
            {
                entity.Success = _runResult.Status == ResultStatus.Success;
            }
            entity.Data = _runResult.Result;
            entity.Message = _runResult.Message;
            return entity;
        }
    }
View Code

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com