Asp.net MVC利用Ajax.BeginForm实现bootstrap模态框弹出,并进行前段验证

1.新建Controller

public ActionResult Index()
        {
            return View();
        }

        public ActionResult Person(int? id)
        {
            //could add code here to get model based on id....
                return PartialView("_Person");
                //calling partial with existing model....
                //return PartialView("_Person", model);

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Person(PersonValidationViewModel model)
        {
            if (!ModelState.IsValid)
            {
                    var errors = GetErrorsFromModelState();
                    return Json(new {success = false, errors = errors});
                //return PartialView("_Person", model);
            }

            //save to persistent store;
            //return data back to post OR do a normal MVC Redirect....
            return Json(new {success = true});  //perhaps you want to do more on return.... otherwise this if block is not necessary....
            //return RedirectToAction("Index");
        }

Controller相关代码

2.新建相应的index

<div class="jumbotron">
    <h1>@ViewBag.Title</h1>
    <p class="lead">Form binding to bootstrap modal with the Ajax Helpers<p>
</div>

@Ajax.ActionLink("Add Person", "Person",null,
new AjaxOptions() {HttpMethod = "Get",UpdateTargetId = "modalContent", InsertionMode = InsertionMode.Replace, OnBegin = "onBegin", OnSuccess = "onSuccess",OnFailure = "onFailure",OnComplete = "onComplete"},
new { id = "btnPerson", @class = "btn btn-lg btn-info" })

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" id="modalContent">
        </div>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script type="text/javascript">
        function onBegin() {
            //alert(‘begin‘);
        }

        function onSuccess() {
            //alert(‘success‘);
        }

        function onComplete() {
            //alert(‘complete‘);
            $(‘#myModal‘).modal(‘show‘);
        }

        function onFailure() {
            alert(‘fail‘);
        }
    </script>
}

index 相关代码

3.弹出模态框用partialView

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Modal with Model & Form</h4>
</div>
<div class="modal-body">
    @using (@Ajax.BeginForm(new AjaxOptions() {HttpMethod = "Post",OnSuccess = "formSuccess(data)"}))
{
        @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BirthDate, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BirthDate)
                @Html.ValidationMessageFor(model => model.BirthDate)
            </div>
        </div>
    </div>

        <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
</div>
}
</div>

<script type="text/javascript">

    function formSuccess(result) {
        if (result.success) {
            $(‘#myModal‘).modal(‘hide‘);
            location.reload();
        } else {
            $.each(result.errors, function(key, val) {
                var container = $(‘span[data-valmsg-for="‘ + key + ‘"]‘);
                container.removeClass("field-validation-valid").addClass("field-validation-error");
                container.html(val[val.length - 1].ErrorMessage);
            });
        }
    }

    $(function () {
        //allow validation framework to parse DOM
        $.validator.unobtrusive.parse(‘form‘);
    });
</script>

partialview

4.前段验证

需加入相关的js文件:jquery.validate.unobtrusive.min.js

view中增加相关js

$(function () {
//allow validation framework to parse DOM
$.validator.unobtrusive.parse(‘form‘);
});

5.相关演示

时间: 2024-08-09 18:46:09

Asp.net MVC利用Ajax.BeginForm实现bootstrap模态框弹出,并进行前段验证的相关文章

bootstrap 模态框中弹出层 input不能获得焦点且不可编辑

bootstrap 模态框中弹出层 input不能获得焦点且不可编辑 问题描述:bs框架支持一层model层的情况下,在模态框中弹出了自定义的弹出层.发现自定义弹出层的输入框不能获得焦点且不可编辑. 解决方法:去除模态框中的"tabindex"属性. <div class="modal fade" tabindex="-1" role="dialog" id="myModal" data-backdr

ASP.NET MVC下Ajax.BeginForm方式无刷新提交表单

有时候,不得不考虑到以下场景问题: 数据库表字段会频繁更改扩展,而流行的重业务的js框架过于依赖json数据接口,导致的问题是,数据库表更改 -> 数据接口更改 -> 前段框架逻辑更改... 一不小心就陷入坑坑洼洼. 这样的话,原来纯ASP.NET MVC绑定的方式,还是可以一用的,因为该方式不用再为那么多js代码烦恼. 不好意思,前面自说自话啊,直接上干货代码了———— Ajax.BeginForm @{ Layout = null; var ajaxOptions = new AjaxOp

ASP.NET MVC利用ajax把action的JavaScript注册到页面并执行

相信大家在做Webform时经常会遇到在页面的后台CS文件中根据数据运行结果修改页面显示样式.显示(隐藏).或者弹出框,当时我们会用到ScriptManage或者Page来向页面注册一段js来实现页面加载显示我们需要的效果. 在MVC中没了ScriptManage.Page对象让我们轻松向页面注册脚本,只能麻烦一点通过ajax来完成. 先决条件: 1.首先需要在加载的页面中引用Jquery包和unobtrusive-ajax <script type="text/javascript&qu

bootstrap删除模态框弹出并询问是否删除【通用删除模态框】

普通的询问是否删除的对话框比较low,可以利用bootstrap的模态框代替普通的对话框来实现删除. 效果: 点删除的时候弹出模态框询问是否删除,点确认的时候将需要删除的ID传到后台进行删除.  过程: 1.界面准备删除模态框: 模态框中隐藏需要删除的ID <!-- 模态框 信息删除确认 --> <div class="modal fade" id="delcfmOverhaul"> <div class="modal-dia

关于【bootstrap modal 模态框弹出瞬间消失的问题】

前提是你没有重复引入bootstrap.js\bootstrap.min.js和modal.js. 一下提供一个小例子. <button class="btn btn-primary btn-lg"  type="button"  data-toggle="modal"data-target="#myModal"> Launch demo modal </button> 注意红字部分type="

bootstrap 工具提示框 弹出框 要事先初始化

工具提示框 初始化: $(function () { $("[data-toggle='tooltip']").tooltip(); }); 弹出框 初始化: $(function () { $("[data-toggle='popover']").popover(); });

去除BOOTSTRAP模态框半透明阴影

当使用bootstrap模态框默认自带半透明阴影,如果想要去除阴影,需要怎么做呢? 今天在项目中我遇到了这个问题,想要去除模态框的阴影,试了好久都没解决.后来问同事的时候才知道,当模态框弹出后,会加上这样一句代码: <div class="modal-backdrop  in"></div> 案例:自带半透明阴影的模态框 1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta char

ASP.NET MVC利用PagedList分页(二)PagedList+Ajax+JsRender

(原文) 昨天在ASP.NET MVC利用PagedList分页(一)的 最后一节提到,一个好的用户体验绝对不可能是点击下一页后刷新页面,所以今天来说说利用Ajax+PagedList实现无刷新(个人绝对局部刷新更准确 些)的分页.其实在PagedList.Mvc中早已经为我们提供好了Ajax分页的各种东东,但是这里我要自己写下. 实现思想: 1.客户端发送Ajax请求.2.服务器端响应请求并将响应结果回传给客户端.3.客户端接收响应结果并进行数据绑定. 实现方案: 大多数人都知道这个思想,但是

MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证

原文:MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证 MVC中,关于往后台提交的方法有: 1.Html.BeginForm():同步 2.Ajax.BeginForm():异步 3.js或jQuery提交后台 本文体验Ajax.BeginForm()方法.   View model using System; using System.ComponentModel.DataAnnotations;   namespace XHelent.Models { public