【问题标题】:AJAX error return ModelState ErrorAJAX 错误返回 ModelState 错误
【发布时间】: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


【解决方案1】:

我刚刚想通了。我知道modelState 是一个数组类型,第二个值是实际输入的电子邮件地址。

所以我将 button.click 事件编辑为:

$("#Create-Btn").on("click",
    function(e) {
        $("form").validate({
            submitHandler: function () {
                e.preventDefault();

                var emailValue = $("#Email").val();

                $.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);
                        toastr.error(status + " - " + error.modelState[emailValue]);
                    }
                });
            }
        });
    });

通过数组括号表示法查找错误消息以及获取尝试提交的电子邮件的实际值就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-27
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多