如果请求是通过 ajax 的,如何检索成功和模型错误并以模式显示

Posted

技术标签:

【中文标题】如果请求是通过 ajax 的,如何检索成功和模型错误并以模式显示【英文标题】:How to retrieve success and model error if request is via ajax and display it in modal 【发布时间】:2022-01-16 02:25:06 【问题描述】:

如果帖子是通过 ajax 调用的,我想知道如何检索成功和模型错误并将其显示在我的模式中?如果成功模式必须关闭并且如果出现错误,则模式应显示自定义错误而不是关闭模式。到目前为止,这是我的代码:

当用户点击保存按钮功能时调用:

    if (result.value) 
    
                    var actionUrl = form.attr('action');
                    var sendData = form.serialize();
    
                    $.post(actionUrl, sendData).done(function (data) 
    
                        //Error here
                        //what code to retrieve error here?
                        //end error
    
                        //Success here
                        swalWithBootstrapButtons.fire(
                            'Saved!',
                            'Your data has been saved.',
                            'success'
                        )
    
                        PlaceHolderElement.find('.modal').modal('hide');
                        //end success
                    );


                 else if (
                    /* Read more about handling dismissals below */
                    result.dismiss === Swal.DismissReason.cancel
                ) 
                

这是我的控制器代码:

     [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Create(string company, MemberVM member)
            
                if (ModelState.IsValid)
                
                    var user = new ApplicationUser  UserName = member.Email, Email = member.Email, SiteName = company, Status=true, DateCreated = DateTime.Now, EmailConfirmed = true ;
                    var result = await _userManager.CreateAsync(user, "Password123!");
                    if (result.Succeeded)
                    
    
                    
                    else
                    
                        foreach (var error in result.Errors)
                        
                            ModelState.AddModelError("", error.Description);
                        
    
                        return PartialView();
                    
    
return PartialView();
    

而且我知道我的验证脚本运行良好,示例截图

【问题讨论】:

***.com/questions/18893814/… 您可以阻止您的模型关闭,稍后您可以返回 json 而不是返回 PartialView,如果您想检查用户是否发出了 ajax 请求,您可以从 Request.IsAjaxRequest 进行检查。 【参考方案1】:

您可以尝试返回错误消息以查看而不是返回 PartialView。并将错误消息放在您想要的位置。

[HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<Dictionary<string, string>> Create(string company, MemberVM member)
            
                Dictionary<string, string> d = new Dictionary<string, string>();
                if (ModelState.IsValid)
                
                    var user = new ApplicationUser  UserName = member.Email, Email = member.Email, SiteName = company, Status=true, DateCreated = DateTime.Now, EmailConfirmed = true ;
                    var result = await _userManager.CreateAsync(user, "Password123!");
                    if (result.Succeeded)
                    
    
                    
                    else
                       
                        foreach (var error in result.Errors)
                        
                            d.Add("propertyName", error.Description);
                        
    
                        return d;
                    
    
return d;
    

查看模态:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post">
                    <div class="form-group">
                        <label asp-for="FirstName" class="control-label"></label>
                        <input asp-for="FirstName" class="form-control" />
                        <span asp-validation-for="FirstName" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="LastName" class="control-label"></label>
                        <input asp-for="LastName" class="form-control" />
                        <span asp-validation-for="LastName" class="text-danger"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="CallJs()">Save changes</button>
            </div>
        </div>
    </div>
</div>

js:

$.post(actionUrl, sendData).done(function (data) 
    
                        //Error here
                        //what code to retrieve error here?
                        //end error
                        if (Object.keys(data).length != 0) 
                        //if the dictionary is not empty,add error to corresponding span of input
                        for (const [key, value] of Object.entries(data)) 
                            $("span[data-valmsg-for=" + key + "]").html(value);
                        
                         else 
                            //if the dictionary is empty,close the modal
                            PlaceHolderElement.find('.modal').modal('hide');
                        
    
                        //Success here
                        swalWithBootstrapButtons.fire(
                            'Saved!',
                            'Your data has been saved.',
                            'success'
                        )
    
                        
                        //end success
                    );

【讨论】:

以上是关于如果请求是通过 ajax 的,如何检索成功和模型错误并以模式显示的主要内容,如果未能解决你的问题,请参考以下文章

判断请求是浏览器页面请求还是ajax进入

如何区分 Ajax 请求和普通 Http 请求?

使用 django 和 ajax 显示表单错误

怎样使用jquery的ajax在发送GET请求是带上entity-body

如何在 iframe 中打开 ajax 成功的引导模式

如何检查请求是通过 HTTP 还是 HTTPS [重复]