【问题标题】:How to trigger Model Validation inside modal? .NET 5如何在模态中触发模型验证? .NET 5
【发布时间】:2021-08-21 16:02:26
【问题描述】:

当我尝试通过错误填充表单来尝试模型验证时遇到问题。 当我尝试使用错误的值(模型验证器无效)提交时,它会重定向到页面(没有模型)。

这是屏幕截图: Customer Index redirect to Customer Create Page when i submit

这是代码

控制器

  //POST CREATE
    [HttpPost]
    [AutoValidateAntiforgeryToken]
    public IActionResult Create(Models.Customer obj)
    {
        if (ModelState.IsValid)
        {
            _db.Customers.Add(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(obj);
    }

    //GET DELETE
    public IActionResult Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }
        var obj = _db.Customers.Find(id);
        if (obj == null)
        {
            return NotFound();
        }
        return PartialView(obj);
    }

型号

public class Customer
{
    [Key]
    public int Id { get; set; }
    [DisplayName("Nama Customer")]
    [Required]
    [MaxLength(81, ErrorMessage ="Tidak boleh melebihi 81 Karakter")]
    public string Nama { get; set; }
    
    public string Alamat { get; set; }
    [Phone]
    [Required]
    public string Telp { get; set; }
}

Index.HTML 按钮创建

<button id="btnAddCustomer" class="btn btn-primary">Tambah Customer</button>

JS

 @section Scripts{
    <script type="text/javascript">
    $(document).ready(function () {
        $("#btnAddCustomer").on("click", function (e) {
        var $buttonClicked = $(this);
        //var id = $buttonClicked.attr('data-id');
        var options = { "backdrop": "static", keyboard: true };
        $.ajax({
            type: "GET",
            url: '@Url.Action("Create", "Customer")',
            contentType: "application/json; charset=utf-8",
            data: null,
            datatype: "json",
            success: function (data) {
                $('#modalBody').html(data);
                $('#modalCustomer').modal(options);
                $('#modalCustomer').modal('show');
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    })
});

创建 CSHTML

<form method="post" asp-action="Create">
<div class="border p-3">
    
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group row">
        <div class="col-4">

        </div>
        <div class="col-4">
            <h2 class="text-black-50 pl-3">Add Customer</h2>
        </div>
        <div class="col-4">

        </div>
        
    </div>
        <div class="row">
            <div class="col-12 form-horizontal">
                <div class="form-group row">
                    <div class="col-12 form-group">
                        <label asp-for="Nama"></label>
                        <input asp-for="Nama" class="form-control" />
                        
                        <span asp-validation-for="Nama" class="text-danger"></span>
                    </div>
                    <br />
                    <div class="col-12 form-group">
                        <label asp-for="Telp"></label>
                        <input asp-for="Telp" class="form-control" />
                        
                        <span asp-validation-for="Telp" class="text-danger"></span>
                    </div>
                    <br />
                    <div class="col-12 form-group">
                        <label asp-for="Alamat"></label>
                        <input type="text" asp-for="Alamat" class="form-control" />
                        @*validasi form*@
                        <span asp-validation-for="Alamat" class="text-danger"></span>
                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-6">

                    </div>
                    <div class="col-6">

                    </div>
                    <div class="col-6">

                    </div>


                </div>
                <div class="form-group row">
                    <div class="col-8 offset-2 row">
                        <div class="col">
                            <input type="submit" class="btn btn-info w-75" value="create" />
                        </div>
                        <div class="col">
                            <a asp-action="Index" class="btn btn-danger w-75">Back</a>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

谢谢(:

【问题讨论】:

    标签: c# asp.net-core-mvc bootstrap-modal .net-5


    【解决方案1】:

    当我尝试使用错误的值提交时(不适用于模型 验证器)它重定向到页面(没有模型)。

    当模型状态无效时,您使用return View(obj);。因此,如果您没有指定视图名称,它将返回带有模型的视图,并且视图名称应该是操作名称(创建)。所以使用你的代码这个结果是正确的。

    这是一个工作演示:

    Index.cshtml:

    <button id="btnAddCustomer" class="btn btn-primary"> Tambah Customer</button>
    
    <div class="modal fade" id="modalCustomer" 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" id="modalBody">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>    
    @section Scripts{
        <script>
            $(document).ready(function () {
            $("#btnAddCustomer").on("click", function (e) {
            var $buttonClicked = $(this);
            //var id = $buttonClicked.attr('data-id');
            var options = { "backdrop": "static", keyboard: true };
            $.ajax({
                type: "GET",
                url: '@Url.Action("Create", "Customer")',
                contentType: "application/json; charset=utf-8",
                data: null,
                datatype: "json",
                success: function (data) {
                    $('#modalBody').html(data);
                    //$('#modalCustomer').modal(options);
                    $('#modalCustomer').modal('show');
                },
                error: function () {
                    alert("Dynamic content load failed.");
                }
            });
        })
    });
        </script>
    }
    

    创建.cshtml:

    @model Customer
    @{
        Layout = null;         //be sure add this...
    }
    <form method="post" asp-action="Create">
        <div class="border p-3">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group row"><div class="col-4"></div><div class="col-4"><h2 class="text-black-50 pl-3">Add Customer</h2></div><div class="col-4"></div></div>
            <div class="row">
                <div class="col-12 form-horizontal">
                    <div class="form-group row">
                        <div class="col-12 form-group">
                            <label asp-for="Nama"></label>
                            <input asp-for="Nama" class="form-control" />
                            <span asp-validation-for="Nama" class="text-danger"></span>
                        </div>
                        <br />
                        <div class="col-12 form-group">
                            <label asp-for="Telp"></label>
                            <input asp-for="Telp" class="form-control" />
                            <span asp-validation-for="Telp" class="text-danger"></span>
                        </div>
                        <br />
                        <div class="col-12 form-group">
                            <label asp-for="Alamat"></label>
                            <input type="text" asp-for="Alamat" class="form-control" />
                            <span asp-validation-for="Alamat" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group row"><div class="col-6"></div><div class="col-6"></div><div class="col-6"></div></div>
                    <div class="form-group row">
                        <div class="col-8 offset-2 row">
                            <div class="col"> 
                                         @*change here..........*@
                                <input type="button" id="btn" class="btn btn-info w-75" value="create" />
                            </div>
                            <div class="col">
                                <a asp-action="Index" class="btn btn-danger w-75">Back</a>
                            </div>
                        </div>
                    </div>
    
                </div>
            </div>
        </div>
    </form>
    

    Create.cshtml中的JS:

    <script>
        $(document).on('click', '#modalCustomer #btn', function () {
            var options = {};
            options.type = "POST";
            options.url = "/Customer/create";
            options.dataType = "JSON";
            options.cache = false;
            options.async = true;
            options.data = $("form").serialize();
            options.success = function (data) {
                //do your stuff...
                $('#modalCustomer').modal('hide');
                 //if you don't want to stay in Index
                 //add the following code..
                // window.location.href = "/home/privacy";
            };
            options.error = function (res) {
                $('#modalBody').html(res.responseText);
            };
            $.ajax(options);
        });
    </script>
    

    更新:

    如果modelstate无效,它会进入options.error并以模态显示错误信息。如果模型状态有效,它将进入options.success,您可以使用window.location.href 重定向或使用$('#modalCustomer').modal('hide'); 隐藏模态框,您自己做吧。

    后端代码应如下所示:

    [HttpPost]
    [AutoValidateAntiforgeryToken]
    public IActionResult Create(Customers obj)
    {
        if (ModelState.IsValid)
        {
            _db.Customers.Add(obj);
            _db.SaveChanges();
            return Json(new { success = true });   //change this...
        }
        return View(obj);
    }
    

    【讨论】:

    • 感谢您的回答。但是我仍然对在创建“做你的事情”中填写 JS 以验证和插入新行感到困惑。那么我必须用该模型填充什么?
    • 嗨@SigitBudi,do your stuff只是一个注释,在ajax回发成功后任何事情都可以自己做。我忘了分享后端代码,现在更新代码。如果我的回答能帮助您解决问题,请记得采纳为答案。如果没有,请记得跟进让我知道。参考:How to accept as answer.Thanks.
    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2023-04-07
    • 2021-02-22
    • 2021-09-13
    相关资源
    最近更新 更多