如何使用带有验证的 jQuery 在 Modal 中制作 .NET MVC 表单 [英] How to make a .NET MVC Form inside a Modal using jQuery with validation

查看:14
本文介绍了如何使用带有验证的 jQuery 在 Modal 中制作 .NET MVC 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想知道如何将这一切放在一起.我已经多次在 .net MVC 页面中构建表单,无论是否经过验证.我已经使用 jQuery 构建了表单,包括验证和不验证.而且我在模态框内构建了表单,但从未使用 MVC.

I am really struggling with knowing how to put this all together. I've built forms inside .net MVC pages plenty of times, with and without validation. And I've built forms using jQuery, with and without validation. And I've built forms inside of a modal, but never with MVC.

我的 原始问题 因为这个表单在一个模态中,所以我需要使用 jQuery 来处理提交.我花了很长时间弄清楚如何将所有这些移动部件放在一起.到目前为止,我还没有找到将所有这些放在一起的教程(或教程组合).

I understand from my original question that because this form is inside a modal that I'll need to use jQuery to handle the submit. I am having a heck of a time figuring out how to put all these moving pieces together. So far, I've not found a tutorial (or combo of tutorials) that puts this all together.

这是我需要的:

  • 在我的 MVC 视图中,有一个用于打开模式的按钮.(这很好用.)
  • 模式打开后,会包含一个带有多个文本字段和下拉菜单的表单.每个都是必需的.(为了使这些字段成为必需的,我会在视图模型中定义这些,就像我通常使用 MVC 表单一样?还是在 jQuery 中创建需求?)
  • 如果用户尝试提交表单并且表单为空或无效,则模式保持打开状态并显示验证消息.(我明白,从我的 原始问题,由于模态的原因,使用直接 MVC 是不可能的,并且需要一些 jQuery.我在这里迷路了.)
  • 如果用户尝试提交表单并且所有字段都有效,则模式关闭,我们点击控制器并将字段保存到数据库.(不知道如何从 jQuery 中逃脱,直接点击普通控制器来处理最终逻辑.)
  • Inside of my MVC view there is a button that opens a modal. (This works fine.)
  • Once the modal opens, it contains a form with several text fields and dropdowns. Each is required. (To make the fields required, would I define these in the view's model, as I normally would with an MVC form? Or do I create the requirements in the jQuery?)
  • If the user attempts to submit the form and they are empty or invalid, the modal stays open and the validation messages appear. (I understand, from my original question, that this is not possible using straight MVC because of the modal, and that some jQuery is needed. I'm lost here.)
  • If the user attempts to submit the form and all fields are valid, then the modal closes, we hit the controller and save the fields to the db. (Not sure how to escape out of the jQuery and just hit the normal controller to handle the final logic.)

谢谢你,杰森,你的帮助!根据您的建议,这就是我的工作方式.

Thank you, Jason, for your help! Based on your suggestions, this is how I got it working.

父视图:

模态:

<div class="modal fade" id="AccountEditModal" tabindex="-1" role="dialog" aria-labelledby="AccountEditModalLabel">
    <div class="modal-dialog modalAccountEdit" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h3><strong>Edit Account Profile - <span class="accountname"></span></strong></h3>
            </div>

            <div class="modal-body">
                <div id="formContent">
                    @Html.Partial("_AccountProfileEdit", new GEDCPatientPortal.Models.AccountProfileEditViewModel())
                </div>
            </div>
        </div>
    </div>
</div>

然后是脚本:

@section Scripts {
    <script>
        $(document).ready(function () {

            $('#AccountEditModal').on('shown.bs.modal', function () {
                $('#myInput').focus()
            })



        $("#AccountEditModal").on("submit", "#form-accountprofileedit", function (e) {
            e.preventDefault();  // prevent standard form submission

            var form = $(this);
            $.ajax({
                url: form.attr("action"),
                method: form.attr("method"),  // post
                data: form.serialize(),
                success: function (partialResult) {
                    $("#formContent").html(partialResult);
                }
            });
        });


        });

    </script>
}

局部视图(缩小版):

@using (Html.BeginForm("AccountProfileEdit", "Account", FormMethod.Post, new { id = "form-accountprofileedit", @class = "full-form" }))
    {


    @Html.CustomTextboxFor(model => model.Address)


    <div style="text-align:right;">
        <button type="submit" id="accountprofileedit-submit" name="accountprofileedit-submit" value="Edit Account" class="btn btn-primary" style="margin-left:5px;">Edit Account</button>
        <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
    </div>
}

控制者:

    [HttpPost]
    public ActionResult AccountProfileEdit(AccountProfileEditViewModel model)
    {
        if (ModelState.IsValid)
        {
            // logic to store form data in DB
        }

        return PartialView("_AccountProfileEdit", model);

    }

推荐答案

您可以使用内置的 MVC 验证脚本以及模型上的数据注释

You can use the built-in MVC validation scripts along with the data annotaions on your model

public class AccountProfileEditViewModel
{
    [Display(Name = "Address")]
    [Required()]
    [StringLength(200)]
    public string Address { get; set; }
}

制作一个局部视图来保存你的模态表单.

Make a partial view to hold your modal form.

_AccountProfileEdit.cshtml

@model AccountProfileEditViewModel

@using(Html.BeginForm("AccountProfileEdit", "Account",
           FormMethod.Post, new { id = "form-accountedit-appt" }) {
    @Html.ValidationSummary(true)

    @Html.LabelFor(m => m.Address)
    @Html.TextBoxFor(m => m.Address)
    @Html.ValidationMessageFor(m => m.Address)
    <button type="submit">Edit</button>
}

然后在您的模态框中引用它.如果你想要预填充模型,你需要渲染一个动作:

Then reference this in your modal box. If you want pre-populated model you'll need to render an action:

<div class="modal-body" id="form-container">
    @Html.Action("AccountProfileEdit", "Account", new { id=account.Id })
</div>

如果您只想要一个空白表格,那么您可以使用:

If you just want a blank form then you can just use:

<div class="modal-body" id="form-container">
    @Html.Partial("_AccountProfileEdit")
</div>

动作使用 id 参数来获取和填充模型

The action uses the id parameter to fetch and populate the model

[HttpGet]
public ActionResult AccountProfileEdit(int id)
{
    AccountProfileEditViewModel model = db.GetAccount(id);  // however you do this in your app

    return PartialView("_AccountProfileEdit", model);
}

AJAX POST

现在您需要 AJAX 来提交此表单.如果您依赖标准表单提交,浏览器将离开您的页面(并关闭您的模式).

Now you'll need AJAX to submit this form. If you rely on a standard form submission the browser will navigate away from your page (and close your modal).

$("#myModal").on("submit", "#form-accountedit", function(e) {
    e.preventDefault();  // prevent standard form submission

    var form = $(this);
    $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),  // post
        data: form.serialize(),
        success: function(partialResult) {
            $("#form-container").html(partialResult);
        }
    });
});

提交事件需要使用事件委托$(staticParent).on(event, target, handler),因为表单内容以后可能会被替换.

You need to use the event delegate $(staticParent).on(event, target, handler) for the submit event because the form content may be replaced later.

发布操作

[HttpPost]
public ActionResult AccountProfileEdit(AccountProfileEditViewModel model)
{
    // Request.Form is model

    if (ModelState.IsValid)
    {
        // do work
        return PartialView("_AccountEditSuccess");
    }

    return PartialView("_AccountProfileEdit", model);
}

客户端验证脚本应该阻止它们提交.但是,如果这以某种方式失败,或者如果您无法在客户端上验证某些内容,那么您就有了 ModelState.IsValid.您还可以手动使服务器端的某些内容无效.

Client-side validation scripts should prevent them from ever submitting. But if that somehow failed or if you can't validate something on the client then you have ModelState.IsValid. You might also invalidate something server-side manually.

_AccountEditSuccess.cshtml

以及成功"的局部视图.

And the "success" partial view.

<div>Success! <button>Click to close</button></div>

无效就是失败,对吧?

来自您的 AJAX 成功处理程序

From your AJAX success handler you have

success: function(partialResult) {
    $("#form-container").html(partialResult);
}

但这里的问题是我们不知道您得到的是成功"还是验证失败".添加 error: function(err){ } 处理程序无济于事,因为验证失败被视为 HTTP 200 响应.在这两种情况下,div 内容都会被替换,用户需要手动关闭模式.种方法可以传递额外的数据来区分这两种情况,但这是另一个长答案.

But the problem here is we don't know if you are getting a "success" or "validation failure". Adding an error: function(err){ } handler won't help because the validation failure is considered a HTTP 200 response. In both cases the div content is replaced the user will need to manually close the modal. There are ways to pass additional data to distinguish both conditions but that's another long answer post.

这篇关于如何使用带有验证的 jQuery 在 Modal 中制作 .NET MVC 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆