MVC 4 模态窗口,局部视图和验证

Posted

技术标签:

【中文标题】MVC 4 模态窗口,局部视图和验证【英文标题】:MVC 4 Modal window, partial view and validation 【发布时间】:2013-04-07 15:51:29 【问题描述】:

我正在使用 MVC4 和实体框架来开发 Web 应用程序。我有一张表,其中列出了我在数据库中拥有的所有人员。对于他们每个人,我可以通过一个模式窗口编辑他们的信息,这是一个部分视图。但是,当我输入一些错误信息时,我的应用程序会将我重定向到我的部分视图。我想要做的是将错误显示在我的模态窗口中。

我的行动:

[HttpGet]
public ActionResult EditPerson(long id)

    var person = db.Persons.Single(p => p.Id_Person == id);

    ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);

    return PartialView("_EditPerson", person);


[HttpPost]
public ActionResult EditPerson(Person person)


    ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);

    if (ModelState.IsValid)
    
        ModelStateDictionary errorDictionary = Validator.isValid(person);

        if (errorDictionary.Count > 0)
        
            ModelState.Merge(errorDictionary);
            return PartialView("_EditPerson", person);
        

        db.Persons.Attach(person);
        db.ObjectStateManager.ChangeObjectState(person, EntityState.Modified);
        db.SaveChanges();
        return View("Index");
    

    return PartialView("_EditPerson", person);

我的部分观点:

@model BuSIMaterial.Models.Person

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit</h3>
</div>
<div>

@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "table"
                    ))


    @html.ValidationSummary()
    @Html.AntiForgeryToken()

    @Html.HiddenFor(model => model.Id_Person)

    <div class="modal-body">
       <div class="editor-label">
            First name :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new  maxlength = 50 )
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <div class="editor-label">
            Last name :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName, new  maxlength = 50 )
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
        <div class="editor-label">
            National number :
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NumNat, new  maxlength = 11 )
            @Html.ValidationMessageFor(model => model.NumNat)
        </div>
        <div class="editor-label">
            Start date :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.StartDate, new  @class = "datepicker", @Value = Model.StartDate.ToString("yyyy/MM/dd") )
            @Html.ValidationMessageFor(model => model.StartDate)
        </div>
        <div class="editor-label">
            End date :
        </div>
        <div class="editor-field">
            @if (Model.EndDate.HasValue)
            
                @Html.TextBoxFor(model => model.EndDate, new  @class = "datepicker", @Value = Model.EndDate.Value.ToString("yyyy/MM/dd") )
                @Html.ValidationMessageFor(model => model.EndDate)
            
            else
            
                @Html.TextBoxFor(model => model.EndDate, new  @class = "datepicker" )
                @Html.ValidationMessageFor(model => model.EndDate)
            
        </div>
        <div class="editor-label">
            Distance House - Work (km) :
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.HouseToWorkKilometers)
            @Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
        </div>
        <div class="editor-label">
            Category :
        </div>
        <div class="editor-field">
            @Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
            @Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) <a href="../ProductPackageCategory/Create">
                Add a new category?</a>
        </div>
        <div class="editor-label">
            Upgrade? :
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Upgrade)
            @Html.ValidationMessageFor(model => model.Upgrade)
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" id="save" type="submit">Save</button>
    </div>


</div>

我在索引视图中的脚本:

        $('.edit-person').click(function () 
               var id = $(this).data("id");
               var url = '/Person/EditPerson/'+id;
               $.get(url, function(data) 

                   $('#edit-person-container').html(data);
                   $('#edit-person').modal('show');

               );
        );

另外,如您所见,我已经为我的文本框设置了一个大小,但在我的模式中,它似乎没有被考虑在内。对这些问题有什么想法吗?

【问题讨论】:

【参考方案1】:

您必须在表单上手动触发验证器,该验证器会动态加载到您的 html 页面中。

试试这个:

在您的视图中使用Ajax.ActionLink 将部分视图的内容加载到您的对话框容器中以避免不必要的 javascript

@Ajax.ActionLink("AjaxLink", "EditPerson", new  PersonID = model.Id_Person , new AjaxOptions  UpdateTargetId = "myModalDialog", HttpMethod = "Post",OnSuccess="OpenDialog(myModalDialog)" )

<div id="myModalDialog" title="" style="display: none">
</div>

在你的 JS 文件中这样做

function OpenDialog(DialogContainerID)

     var $DialogContainer = $('#' + DialogContainerID);
     var $jQval = $.validator; //This is the validator
     $jQval.unobtrusive.parse($DialogContainer); // and here is where you set it up.
     $DialogContainer.modal();

     var $form = $DialogContainer.find("form");
     $.validator.unobtrusive.parse($form);

     $form.on("submit", function (event)
     
             var $form = $(this);

             //Function is defined later...
             submitAsyncForm($form,
             function (data)
             
                     $DialogContainer.modal("hide");
                     window.location.href = window.location.href;

             ,
             function (xhr, ajaxOptions, thrownError)
             
                     console.log(xhr.responseText);
                     $("body").html(xhr.responseText);
             );
             event.preventDefault();
     );


//This is the function that will submit the form using ajax and check for validation errors before that.
function submitAsyncForm($formToSubmit, fnSuccess, fnError)

        if (!$formToSubmit.valid())
                return false;

        $.ajax(
                type: $formToSubmit.attr('method'),
                url: $formToSubmit.attr('action'),
                data: $formToSubmit.serialize(),

                success: fnSuccess,
                error: fnError

        );


【讨论】:

谢谢。我应该把这个函数放到我的局部视图中就可以了吗? @Traffy 在这里我添加了脚本的完整用法以便更好地解释自己。【参考方案2】:

您需要通过 JavaScript 处理编辑表单的提交,否则它会将您重定向到您的局部视图。

你可以这样做:

$('form.edit').submit(function(e) 

    e.preventDefault();

    $.ajax(
        type: 'POST',
        url: '/Person/EditPerson/'
        data:  person: $(this).serialize() ,
        success: function(data) 

            /* Add logic to check if successful edit or with errors. Or just return true when edit is successful. */

            $('#edit-person-container').html(data);
        
    );

);

【讨论】:

感谢您的回答,我会尝试并告诉您。【参考方案3】:

这对我有用:

//allow the validation framework to re-prase the DOM
jQuery.validator.unobtrusive.parse();    
//or to give the parser some context, supply it with a selector
//jQuery validator will parse all child elements (deep) starting
//from the selector element supplied
jQuery.validator.unobtrusive.parse("#formId");
// and then:
$("#formId").valid()

取自Here

【讨论】:

【参考方案4】:

您是否将以下脚本添加到布局或包含部分的视图中? jquery.unobtrusive-ajax.min.js。这是异步请求所必需的,默认情况下不添加,但存在于脚本下的新解决方案中。

【讨论】:

以上是关于MVC 4 模态窗口,局部视图和验证的主要内容,如果未能解决你的问题,请参考以下文章

MVC 4 使用 Bootstrap 编辑模态表单

在 MVC5 中提交时,带有表单的模态窗口不会关闭

使用jquery ui在mvc 4中打开带有参数的模态窗口

通过 MVC 局部视图注入时,Bootstrap 模态显示和隐藏事件未触发

谷歌地图不能在模态弹出窗口上呈现

模态视图重新加载内容 (Bootstrap MVC ASP.NET)