在我看来,显示来自 Web Api 服务的 modelState 错误列表? (MVC 4)
Displaying modelState errorlist from a Web Api service in my view? (MVC 4)
我正在使用数据注释来验证我计划添加的任何模型,并在违反规则时将验证消息返回到我的视图,方法如下:
// 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));
}
}
下面是我处理返回错误的方法,我的issue jqXHR好像是空的???我显示我的 modelState 消息列表??:
.....
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; }
}
这里有一些事情:
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) 我怀疑您的网站 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 错误块中的响应对象。
我正在使用数据注释来验证我计划添加的任何模型,并在违反规则时将验证消息返回到我的视图,方法如下:
// 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));
}
}
下面是我处理返回错误的方法,我的issue jqXHR好像是空的???我显示我的 modelState 消息列表??:
.....
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; }
}
这里有一些事情:
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) 我怀疑您的网站 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 错误块中的响应对象。