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

转(http://www.cnblogs.com/bobo-show/p/4679697.html

1.新建Controller

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

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 相关代码
View Code

3.弹出模态框用partialView _Person

<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
View Code

4.前段验证

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

view中增加相关js

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

Model

 public class PersonValidationViewModel
    {
        [StringLength(10,MinimumLength=2)]
        public string FirstName { get; set; }
        public string LastName { get; set; }
         [DataType(DataType.Date)]
        public string BirthDate { get; set; }
    }

 

在上一篇在Views的多级文件夹中,我们在Controlls文件夹下新建了文件夹,那么对于partialView怎么处理呢?在admin_routing方法中添加如下代码

 PartialViewLocationFormats = new[]
 {
                "~/Views/Shared/{0}.cshtml",
                 "~/Views/{1}/{0}.cshtml",
                "~/Views/Admin/{1}/{0}.cshtml"//自定义QMRisk的视图
 };

即可在Views/Admin/WebUser文件夹下添加PartialView _Person
效果图

 

posted @ 2017-08-11 15:45  cpcpc  阅读(874)  评论(0编辑  收藏  举报