【发布时间】:2017-11-01 14:03:09
【问题描述】:
在我的创建页面上,我使用 ajax 并在创建人员时调用我的 api 控制器:
<script>
$(document).ready(function() {
var newUrl = '@Url.Action("Index", "PersonInformations")';
var settings = {};
settings.baseUri = '@Request.ApplicationPath';
var infoGetUrl = "";
if (settings.baseUri === "/ProjectNameOnServer") {
infoGetUrl = settings.baseUri + "/api/personinformations/";
} else {
infoGetUrl = settings.baseUri + "api/personinformations/";
}
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
//console.log(jqXHR.responseText);
toastr.error(status + " - " + error.message);
}
});
}
});
});
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
});
</script>
这是我的 PersonInformations API 控制器中的方法:
[ResponseType(typeof(PersonInformation))]
public IHttpActionResult PostPersonInformation(PersonInformation personInformation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var lstOfPersons = db.PersonInformations.Where(x => x.deleted == false).ToList();
if (lstOfPersons.Any(
x =>
x.FirstName == personInformation.FirstName && x.LastName == personInformation.LastName &&
x.AId == personInformation.AgencyId && x.ID != personInformation.ID))
{
ModelState.AddModelError("", "This person already exists!");
return BadRequest(ModelState);
}
if (
lstOfPersons.Any(
x => x.Email.ToLower() == personInformation.Email.ToLower() && x.ID != personInformation.ID))
{
ModelState.AddModelError(personInformation.Email, "This email already exists!");
return BadRequest(ModelState);
}
personInformation.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.FirstName);
personInformation.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.LastName);
db.PersonInformation.Add(personInformation);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = personInformation.ID }, personInformation);
}
现在,当我对此进行测试并故意输入一封已存在的电子邮件时,ajax 请求会出错但返回消息:
错误 - 请求无效
但是当我使用console.log(jqXHR.responseText)
我明白了:
Create
{
"$id": "1",
"message": "The request is invalid.",
"modelState": {
"$id": "2",
"test@test.com": [
"This email already exists!"
]
}
}
如何获取"This email already exists!" 作为错误消息?
【问题讨论】:
-
我认为这也应该有效:
return new HttpResponseMessage(HttpStatusCode.BadRequest, "This email already exists!");如果您只需要错误消息 -
或者你将不得不从响应中的modelState获取你需要的消息
-
通过在 JSON 中找到正确的位。你试过什么?
-
@ADyson 想通了。检查我的答案
-
@TheUknown 想通了。检查我的答案
标签: ajax asp.net-mvc asp.net-web-api