如何在 bootstrap 模式中触发 ASP.Net 核心模型验证和远程属性

How to trigger ASP.Net core model validation and remote attribute in bootstrap modal

我想知道如何在提交前触发 bootstrap 模态弹出窗口中的模型验证? 我想从我的模式弹出窗口触发必需的和远程属性验证

这是我的模型代码:

    public class Employee
    {
        public int Id { get; set; }

[Required]
        [Remote("CheckFirstName", "Employees", ErrorMessage = "FirstName already exists.")]
        public string FirstName { get; set; }

        //code here
    }

我的控制器代码:

    public IActionResult Create()
        {
            Employee emp = new Employee();
            return PartialView("_EmployeePartial", emp);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,MI")] Employee employee)
        {
            //code here
            return View(employee);
        }

[AcceptVerbs("Post", "Get")]
public IActionResult CheckFirstName(string fname){
//code here
}

我的员工部分代码:

@model CrudApp.Models.Employee
<!-- Modal -->
<div class="modal fade" id="addEmployee" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <form asp-action="Create">
                    //code here
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-save="modal">Save changes</button>
            </div>
        </div>
    </div>
</div>

调用模态的代码:

<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addEmployee"
        data-url="@Url.Action("Create")">Create</button>

JS代码:

    var PlaceHolderElement = $('#PlaceHolderHere');
    $('button[data-toggle="ajax-modal"]').click(function (event) {

        var url = $(this).data('url');
        $.get(url).done(function (data) {
            PlaceHolderElement.html(data);
            PlaceHolderElement.find('.modal').modal('show');
        });
    });

    PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {

        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var sendData = form.serialize();
        $.post(actionUrl, sendData).done(function (data) {
            PlaceHolderElement.find('.modal').modal('hide');
        });
    });

您正在触发您的控制器中不存在的 CheckFirstName 操作。

public IActionResult CheckFirstName(string FirstName)
{
   // code to validate the FirstName
   
   return Json(result); //return result in json example your validation message.
}

这将在您在 FirstName 文本框中输入内容时触发。

由于员工创建表单是动态添加到主表单中的,并且您是通过 JQuery 方法提交表单,因此要触发验证,您必须在表单上设置客户端验证 (在显示弹出模型之后)。检查以下代码:

Index.cshtml(主页):

<div id="PlaceHolderHere"></div>

<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addEmployee"
        data-url="@Url.Action("Create")">
    Create
</button>

@section Scripts{   
  @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
        $(function () {
            var PlaceHolderElement = $('#PlaceHolderHere');
            $('button[data-toggle="ajax-modal"]').click(function (event) {

                var url = $(this).data('url');
                $.get(url).done(function (data) {
                    PlaceHolderElement.html(data);
                    PlaceHolderElement.find('.modal').modal('show');
                    var form = PlaceHolderElement.find('.modal').find("form");
                    //enable client side validation.
                    $.validator.unobtrusive.parse(form);
                });
            });

            PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {

                var form = $(this).parents('.modal').find('form');
                //check whether the form is valid or not
                if (form.valid()) {
                    var actionUrl = form.attr('action');
                    var sendData = form.serialize();

                    $.post(actionUrl, sendData).done(function (data) {
                        PlaceHolderElement.find('.modal').modal('hide');
                    });
                }
                
            });
        });
    </script>
}

控制器代码如下:

    public IActionResult Create()
    {
        Employee emp = new Employee();
        return PartialView("_EmployeePartial", emp);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,MI")] Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return RedirectToAction(nameof(Index));
        }
        //code here
        return View(employee);
    }

    [AcceptVerbs("Post", "Get")]
    public IActionResult CheckFirstName(string FirstName)
    {
        var emplist = new List<string>() { "AA", "BB", "CC" };

        if (emplist.Contains(FirstName))
        {
            return Json(false);
        }

        //code here
        return Json(true);
    }

那么,结果是这样的:

[注意]:要启用客户端验证,我们应该像这样添加客户端验证脚本引用:@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}。更多详细信息,请参阅 Client-side validation