【问题标题】:Displaying modelState errorlist from a Web Api service in my view? (MVC 4)在我的视图中显示来自 Web Api 服务的 modelState 错误列表? (MVC 4)
【发布时间】:2015-03-11 00:26:04
【问题描述】:

我正在使用数据注释来验证我计划添加的任何模型,并在规则被破坏时将验证消息返回到我的视图中,方法如下:

 // POST api/Issues
        public HttpResponseMessage PostIssues(Issues issues)
        {
            HttpResponseMessage response;

            if (ModelState.IsValid)
            {
                //db.Issues.Add(issues);
                //db.SaveChanges();
                bool isValid = _unitOfWork.IssuesRepository.Insert(issues);

                if (!isValid)
                {
                    RetrieveModelStateErrors("Insert Issues", _unitOfWork.IssuesRepository.ValidationDictionary);
                    Dictionary<string, string> _errorMessages = _unitOfWork.IssuesRepository.ErrorMessages;

                    response = Request.CreateResponse(HttpStatusCode.BadRequest, StaticUtility.ConvertModelState_ToJDictionary(ModelState));
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.OK, issues);
                    //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = issues.IssueID }));
                }

                return response;

            }
            else
            {
                return response = Request.CreateResponse(HttpStatusCode.BadRequest, StaticUtility.ConvertModelState_ToJDictionary(ModelState));
            }
        }

这是我如何处理返回的错误,我的问题 jqXHR 似乎是空的???我显示我的模型状态消息列表??:

....

 success: function (result) {
                        alert("Saved");
                    },
                    error: function (jqXHR, exception) {
                        extractErrors(jqXHR, validator);
                    }

.....

function extractErrors(jqXhr, validator) {

  var data = JSON.parse(jqXhr.responseText), errors = {};

        for (var i = 0; i < data.length; i++) { // add each error to the errors object
            alert("inside here!!");
            var errormessage = data[i].value;
            errors[data[i].key] = errormessage;
        }

        validator.showErrors(errors); // show the errors using the validator object
    }

这是 ConvertModelState_ToJDictionary:

 public static Dictionary<string, string> ConvertModelState_ToJDictionary(ModelStateDictionary modelStateDictionary)
        {
            int x = 0;
            Dictionary<string, string> ErrorMessagesList = new Dictionary<string, string>();
            foreach (var modelState in modelStateDictionary.Values)
            {
                string key1 = modelStateDictionary.Keys.ToList()[x];
                foreach (var error in modelState.Errors)
                {
                    ErrorMessagesList.Add(key1, error.ErrorMessage);
                }
                x++;
            }
            return ErrorMessagesList;
        } 

这里的验证规则:

 public partial class Issues : IValidatableObject
    {
        public IEnumerable<ValidationResult> Validate(ValidationContext validattionContext)
        {
            if (string.IsNullOrEmpty(SEID) )
                yield return new ValidationResult("SEID Cannot be empty", new[] { "SEID" });
            //if (IssueID == 0)
            //    yield return new ValidationResult("IssueID Cannot be 0", new[] { "IssueID" });
        }

    }

我的模特:

public partial class Issues
    {
        public int IssueID { get; set; }
        public string LinkingField { get; set; }
        public Nullable<System.DateTime> DateAdded { get; set; }
        public Nullable<System.DateTime> IRSRcvdDate { get; set; }
        public Nullable<System.DateTime> FrivRcvdDate { get; set; }
        public string SEID { get; set; }
        public string ProgramCode { get; set; }
        public string TxPd { get; set; }
        public string ActionCode { get; set; }
        public Nullable<System.DateTime> ActionDate { get; set; }
        public Nullable<System.DateTime> CloseDate { get; set; }
        public Nullable<int> ArgCode { get; set; }
        public string Promoter { get; set; }
        public string Preparer { get; set; }
        public Nullable<decimal> RevenueProtected { get; set; }
        public Nullable<int> Cnt { get; set; }
        public Nullable<bool> Select { get; set; }
        public Nullable<System.DateTime> FollowUpDate { get; set; }
        public Nullable<decimal> ErrRefund { get; set; }
        public string SCCode { get; set; }
        public string RcvingTeam { get; set; }
        public Nullable<System.DateTime> AssignDate { get; set; }
        public string RefEIN { get; set; }
        public string XTIN { get; set; }
        public Nullable<System.DateTime> StatuteDate { get; set; }
        public string CISNum { get; set; }
        public string FormFiled { get; set; }
        public string ThirdParty { get; set; }
        public string Charact { get; set; }
        public string Remarks { get; set; }
        public string Notary { get; set; }
        public string LetName { get; set; }
        public string EFIN { get; set; }
        public Nullable<System.DateTime> L3176G_Date { get; set; }
        public Nullable<bool> Single { get; set; }
        public Nullable<bool> Joint { get; set; }
        public Nullable<bool> CleanUpNeed { get; set; }
        public Nullable<bool> CleanUpDone { get; set; }
        public Nullable<bool> Paperless { get; set; }
    }

【问题讨论】:

  • 您的result 是空的吗?你在使用 Razor 吗?
  • 它去错误功能?是说,我应该重写为
  • 错误:函数(结果){...
  • 使用 Jquery,它是一个 ajax 调用...不需要剃须刀
  • 好吧,ajax 调用中的模型状态错误和错误处理不是一回事。 Modelstate 错误在 success 回调中处理...这就是为什么我询问 Razor...

标签: jquery asp.net-mvc-4 asp.net-web-api


【解决方案1】:

这里有几件事:

1) 您的ajax 呼叫是否期待json 响应? (例如dataType : "JSON",)它是否得到json 作为响应?这可能是您的响应对象为空的原因。您可以使用 Chrome 中的开发者控制台或其他浏览器实用程序之一来确保您确实获得了json

2) 无法从您的示例中确定您的响应对象的结构是 StaticUtility.ConvertModelState_ToJDictionary(ModelState),因此很难帮助您访问它。通常,您可能希望以不同于处理500 错误的方式处理400 HTTP 错误,以及以不同于其他400 错误的方式处理基于模型状态的400 错误。

例如:

error: function(xhr, status, error){
   switch(xhr.status){
      case 400:
         // parse modelstate errors:
         parseMSErrors(xhr, validator);
         // or do something else
         break;
   }
}

3) 我怀疑您的 Web API 可能没有返回 JSON 对象。除非您有某种形式的过滤器设置,否则请尝试以下操作: - 添加对Newtonsoft JSON 或其他JSON 序列化程序的引用 - 尝试以下 API 响应:

string jsonResp = JsonConvert.SerializeObject(StaticUtility.ConvertModelState_ToJDictionary(ModelState));

return response = Request.CreateResponse(HttpStatusCode.BadRequest, jsonResp);

如果您在 ajax 中指定 JSON,成功访问您的 API,并返回 JSON(如指定),那么您应该能够访问 ajax 错误块中的响应对象。

【讨论】:

  • 我还是 web api 的新手,还在尝试弄明白。添加更多细节
  • 当我通过 chrome 运行它时,我在 POST 期间看到“400:错误请求”,没有返回 JSON 对象
  • 如何将错误字典作为 Json 对象从我的 ajax 调用中迭代?
  • 您是否在 ajax 调用中指定 dataType: "JSON"
  • 是的,没有帮助?
猜你喜欢
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
相关资源
最近更新 更多