如何使用jQuery与验证一个模式里面一个.NET MVC格式 [英] How to make a .NET MVC Form inside a Modal using jQuery with validation

查看:108
本文介绍了如何使用jQuery与验证一个模式里面一个.NET MVC格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的知道如何把这个一起奋斗。我已经建立了.NET MVC的网页很多次,有和没有验证的内部形式。我已经使用jQuery,有和没有验证的建筑形式。而且我已经建立了一个表格模式里面,但从来没有与MVC。

我从<一个明白href=\"http://stackoverflow.com/questions/31039001/asp-net-mvc-need-help-putting-a-form-inside-a-bootstrap-modal?noredirect=1#comment50102744_31039001\">original 的问题,因为这种形式,我需要使用jQuery处理模式内提交。我有一个时间赫克搞清楚如何把所有这些运动拼在一起。到目前为止,我还没有发现这把一起教程(或教程的组合)。

这就是我需要:


  • 在我的MVC视图,有是打开一个模式的按钮。的(这是工作的罚款。)

  • 一旦打开模式,它包含几个文本字段和下拉列表的形式。每个是必需的。的(为了使所需的字段,我会在视图模型中定义这些,因为我通常会用一个MVC形成的?还是我创建了jQuery的要求?)

  • 如果用户尝试提交表单,他们是空的或无效,模态保持断开状态,验证消息出现。的(我的理解,从我的<一个href=\"http://stackoverflow.com/questions/31039001/asp-net-mvc-need-help-putting-a-form-inside-a-bootstrap-modal?noredirect=1#comment50102744_31039001\">original问题,这是不可能的使用直MVC,因为模态的,那就是需要一些jQuery。我在这里丢失。)

  • 如果用户尝试提交表单,所有的字段都有效,那么模态关闭,我们打的控制器和域保存到数据库。的(不知道如何逃出了jQuery的,只是打了正常的控制器来处理最后的逻辑。)

编辑:

感谢您,杰森,你的帮助!根据您的建议,这是我得到它的工作。

父视图:

模态:

 &LT; D​​IV CLASS =模式变脸ID =AccountEditModal的tabindex = -  1角色=对话框中的咏叹调-labelledby =AccountEditModalLabel&GT;
    &LT; D​​IV CLASS =模式-对话框modalAccountEdit角色=文件&GT;
        &LT; D​​IV CLASS =模式内容&GT;
            &LT; D​​IV CLASS =模头&GT;
                &LT;按钮式=按钮级=关闭数据解雇=莫代尔ARIA标签=关闭&GT;&LT;跨度ARIA隐藏=真&GT;&安培;倍;&LT; / SPAN&GT; &LT; /按钮&GT;
                &LT; H3&GT;&LT;强&gt;编辑帐户配置文件 - &LT;跨度类=ACCOUNTNAME&GT;&LT; / SPAN&GT;&LT; / STRONG&GT;&LT; / H3&GT;
            &LT; / DIV&GT;            &LT; D​​IV CLASS =模体&GT;
                &LT; D​​IV ID =formContant&GT;
                    @ Html.Partial(_ AccountProfileEdit,新GEDCPatientPortal.Models.AccountProfileEditViewModel())
                &LT; / DIV&GT;
            &LT; / DIV&GT;
        &LT; / DIV&GT;
    &LT; / DIV&GT;
&LT; / DIV&GT;

然后这里的脚本:

  @section脚本{
    &LT;脚本&GT;
        $(文件)。就绪(函数(){            $('#AccountEditModal')。在('shown.bs.modal',函数(){
                $('#myInput')。重点()
            })        $(#AccountEditModal)。在(提交,#表单accountprofileedit功能(E){
            亦即preventDefault(); // prevent标准表单提交            变种形式= $(本);
            $阿贾克斯({
                网址:form.attr(行动),
                方法:form.attr(办法),//岗位
                数据:form.serialize(),
                成功:函数(partialResult){
                    $(#formContent)HTML(partialResult);
                }
            });
        });
        });    &LT; / SCRIPT&GT;
}

局部视图(瘦身):

  @using(Html.BeginForm(AccountProfileEdit,帐户,FormMethod.Post,新{ID =表单accountprofileedit,@class =全格式} ))
    {
    @ Html.CustomTextboxFor(型号=&GT; model.Address)
    &LT; D​​IV的风格=文本对齐:权利;&GT;
        &LT;按钮式=提交ID =accountprofileedit提交NAME =accountprofileedit提交VALUE =编辑帐户级=BTN BTN-小学的风格=保证金左:为5px;&gt;编辑帐户&LT ; /按钮&GT;
        &LT;按钮式=按钮级=BTN BTN-主要数据解雇=模式&GT;取消&LT; /按钮&GT;
    &LT; / DIV&GT;
}

控制器:

  [HttpPost]
    公众的ActionResult AccountProfileEdit(AccountProfileEditViewModel模型)
    {
        如果(ModelState.IsValid)
        {
            //逻辑存储在数据库表单数据
        }        返回PartialView(_ AccountProfileEdit模型);    }


解决方案

您可以使用内置的MVC验证脚本与模型

数据annotaions一起

 公共类AccountProfileEditViewModel
{
    [显示(NAME =地址)
    [需要()]
    [StringLength(200)]
    公共字符串地址{搞定;组; }
}

请的局部视图来保存你的模式窗体。

_AccountProfileEdit.cshtml

  @model AccountProfileEditViewModel@using(Html.BeginForm(AccountProfileEdit,帐户,
           FormMethod.Post,新{ID =表单accountedit-聘任}){
    @ Html.ValidationSummary(真)    @ Html.LabelFor(M = GT; m.Address)
    @ Html.TextBoxFor(M = GT; m.Address)
    @ Html.ValidationMessageFor(M = GT; m.Address)
    &LT;按钮式=提交&gt;编辑&LT; /按钮&GT;
}

然后在你的模式对话框引用此。如果你想pre-填充模式,你需要渲染一个动作:

 &LT; D​​IV CLASS =模体ID =形式的容器&GT;
    @ Html.Action(AccountProfileEdit,帐户,新{ID = account.Id})
&LT; / DIV&GT;

如果你只是想要一个空白表格,然后你可以使用:

 &LT; D​​IV CLASS =模体ID =形式的容器&GT;
    @ Html.Partial(_ AccountProfileEdit)
&LT; / DIV&GT;

该操作使用 ID 参数来获取和填充模式

  [HTTPGET]
公众的ActionResult AccountProfileEdit(INT ID)
{
    AccountProfileEditViewModel模型= db.GetAccount(ID);然而//你在你的应用做到这一点    返回PartialView(_ AccountProfileEdit模型);
}

AJAX POST

现在,您需要AJAX提交此表。如果你依赖于一个标准的表单提交,浏览器会从你的页面进行浏览,(并关闭您的模态)。

  $(#myModal)。在(提交,#表单accountedit功能(E){
    亦即preventDefault(); // prevent标准表单提交    变种形式= $(本);
    $阿贾克斯({
        网址:form.attr(行动),
        方法:form.attr(办法),//岗位
        数据:form.serialize(),
        成功:函数(partialResult){
            $(#形式的容器)HTML(partialResult);
        }
    });
});

您需要使用事件委托 $(staticParent)。在(事件,目标处理)的提交事件,因为形式的内容可能会被以后替换。

邮政动作

  [HttpPost]
公众的ActionResult AccountProfileEdit(AccountProfileEditViewModel模型)
{
    //的Request.Form是模型    如果(ModelState.IsValid)
    {
        // 做工作
        返回PartialView(_ AccountEditSuccess);
    }    返回PartialView(_ AccountProfileEdit模型);
}

客户端验证脚本应该prevent他们曾经提交。但是,如果以某种方式失败,或者如果您无法验证客户端上的东西,那么你必须 ModelState.IsValid 。您也可以手动一些无效的服务器端。

_AccountEditSuccess.cshtml

和成功的局部视图。

 &LT; D​​IV&GT;成功! &LT;按钮和gt;点击关闭&LT; /按钮&GT;&LT; / DIV&GT;

无效是一个失败,对吧?

从你的AJAX成功处理程序必须

 成功:函数(partialResult){
    $(#形式的容器)HTML(partialResult);
}

但这里的问题是,我们不知道,如果你得到一个成功或验证失败。添加错误:功能(错误){} 处理程序将没有帮助,因为验证失败被认为是一个的 HTTP 200 的响应。在这两种情况下,格内容被替换的用户将需要手动关闭模式。有的方式来传递更多的数据来区分这两个条件,但这是另一个长的答案后。

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.

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.

Here's what I need:

  • Inside of my MVC view, there is a button that opens a modal. (This is working 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.)

EDIT:

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

The Parent View:

The modal:

<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="formContant">
                    @Html.Partial("_AccountProfileEdit", new GEDCPatientPortal.Models.AccountProfileEditViewModel())
                </div>
            </div>
        </div>
    </div>
</div>

And then here's the scripts:

@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>
}

The Partial View (slimmed down):

@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>
}

The Controller:

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

        return PartialView("_AccountProfileEdit", model);

    }

解决方案

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>

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

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);
        }
    });
});

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

Post Action

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

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

    return PartialView("_AccountProfileEdit", model);
}

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>

Not Valid is a Fail, Right?

From your AJAX success handler you have

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

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与验证一个模式里面一个.NET MVC格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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