如何使用带有验证的jQuery在Modal中创建.NET MVC表单

Cas*_*ton 21 forms asp.net-mvc jquery modal-dialog

我真的很想知道怎么把这些放在一起.我已经在.net MVC页面中构建了很多次表单,无论有没有验证.我使用jQuery构建了表单,有和没有验证.我已经在模态中构建了表单,但从未使用过MVC.

我从原来的问题中理解,因为这个形式在一个模态中,我需要使用jQuery来处理提交.我正好想弄清楚如何把所有这些活动的部分组合在一起.到目前为止,我还没有找到将这些全部放在一起的教程(或教程组合).

这就是我需要的:

  • 在我的MVC视图中,有一个按钮可以打开一个模态. (这很好.)
  • 模态打开后,它包含一个包含多个文本字段和下拉列表的表单.每个都是必需的. (为了使字段成为必需字段,我是否会在视图的模型中定义它们,就像我通常使用MVC表单一样?或者我是否在jQuery中创建需求?)
  • 如果用户尝试提交表单并且它们为空或无效,则模式保持打开状态并显示验证消息. (我理解,从我最初的问题来看,使用直接MVC是不可能的,因为模态,并且需要一些jQuery.我迷失在这里.)
  • 如果用户尝试提交表单并且所有字段都有效,则模态关闭,我们点击控制器并将字段保存到数据库. (不知道如何逃离jQuery,只需点击普通控制器来处理最终的逻辑.)

编辑:

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

父视图:

模式:

<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>
Run Code Online (Sandbox Code Playgroud)

接下来是脚本:

@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>
}
Run Code Online (Sandbox Code Playgroud)

局部视图(瘦身):

@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>
}
Run Code Online (Sandbox Code Playgroud)

控制者:

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

        return PartialView("_AccountProfileEdit", model);

    }
Run Code Online (Sandbox Code Playgroud)

Jas*_*sen 35

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

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

制作部分视图以保存您的模态表单.

_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>
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

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

    return PartialView("_AccountProfileEdit", model);
}
Run Code Online (Sandbox Code Playgroud)

AJAX POST

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

$("#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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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

发布行动

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

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

    return PartialView("_AccountProfileEdit", model);
}
Run Code Online (Sandbox Code Playgroud)

客户端验证脚本应该阻止它们提交.但如果那种方式失败了,或者如果你无法在客户端验证某些东西,那么你就有了ModelState.IsValid.您也可能手动使服务器端无效.

_AccountEditSuccess.cshtml

而"成功"的局部观点.

<div>Success! <button>Click to close</button></div>
Run Code Online (Sandbox Code Playgroud)

无效是失败的,对吧?

从您的AJAX成功处理程序

success: function(partialResult) {
    $("#form-container").html(partialResult);
}
Run Code Online (Sandbox Code Playgroud)

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