Returning BadRequest in ASP.Net Core MVC to Microsoft jQuery Unobtrusive Ajax post has ModelState undefined

可紊 提交于 2019-12-11 08:26:24

问题


THE PROBLEM

I am trying to return service side validation errors from ModelState using BadRequest(ModelState) but when I try to assign the the jQuery ModelState from xhr.responseText I am getting undefined error in javascript. I am using ASP.Net Core 1.0.1 with Microsoft.jQuery.Unobtrusive.Ajax 3.2.3.

THE CODE

Controller Action

public async Task<IActionResult> ApplySanction(SanctionViewModel model)
{
    try
    {
        if (ModelState.IsValid)
        {
            //update database
            return RedirectToAction("Details");
        }
        else
        {
            return BadRequest(ModelState);
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.ToString());
    }
}

View (JavaScript)

function AjaxOnFailure(xhr, status, error) {
    console.log(xhr.responseText);

    var errText = "";
    var response = null;
    var errors = [];
    var errorsString = "";
    if (xhr.status == 400) {
        try {
            response = JSON.parse(xhr.responseText);
            console.log(response);
        }
        catch (e) {
            errText = "Error: " + xhr.status + " - " + error;
        }
    }
    if (response != null) {
        var modelState = response.ModelState; //This is returning undefined
        console.log(modelState);
        for (var key in modelState) {
            if (modelState.hasOwnProperty(key)) {
                for (var i = 0; i < modelState[key].length; i++) {
                    errorsString = (errorsString == "" ? "" : errorsString + "<br/>") + modelState[key][i];
                    errors.push(modelState[key][i]);
                }
            }
        }
    }
    if (errorsString != "") { 
        errText = "Validation Error: " + errorsString;
    } 

    console.log(errText);
    var errIcon = "fa fa-exclamation-circle"
    document.getElementById("modalErrorIcon").className = errIcon;
    document.getElementById("modalErrorText").innerHTML = errText;
}

View (Form)

<form asp-controller="Client" asp-action="ApplySanction" class="form-horizontal" data-ajax="true" data-ajax-method="POST" data-ajax-success="CloseModal(xhr, status, '#sanctionModal')" data-ajax-failure="AjaxOnFailure(xhr, status, error)">
    <div class="modal fade" id="sanctionModal" tabindex="-1" role="dialog" aria-labelledby="sanctionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="sanctionModalLabel">Sanction Reason</h4>
                </div>
                <div class="modal-body">
                    <input type="hidden" asp-for="ID" />
                    <div class="form-group">
                        <div class="col-sm-10">
                            <textarea asp-for="SanctionReason" class="form-control" autofocus></textarea>
                            <span asp-validation-for="SanctionReason" class="text-danger" />
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="text-danger pull-left">
                        <i id="modalErrorIcon" class=""></i>
                        <span id="modalErrorText"></span>
                    </div>
                    <button type="submit" class="btn btn-primary">Save</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</form>

THE RESULTS

Javascript Debug Session

Console Log

THE QUESTIONS

  1. Why is my ModelState undefined in my ajax response?

  2. What is the point of using javascript to show validation errors after server side validation? I ask this because I would assume my server side validation only kicks in if a user has javascript disabled on hence client side validation is bypassed. Therefore how can the javascript execute to show the validation errors return by the server ModelState since it's still disabled?

来源:https://stackoverflow.com/questions/40121982/returning-badrequest-in-asp-net-core-mvc-to-microsoft-jquery-unobtrusive-ajax-po

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!