关闭包含 ASP MVC Ajax 表单的模式窗口 [英] Close modal window containing ASP MVC Ajax form

查看:14
本文介绍了关闭包含 ASP MVC Ajax 表单的模式窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 web 应用程序中,我在模式窗口中使用 ASP MVC Ajax 表单.我不使用任何特定的 jQuery 代码,只使用一些打开模态窗口的代码(即 showModal() 函数):

in a webapp I'm using an ASP MVC Ajax form in a modal window. I do not use any specific jQuery code, only some to open the modal window (i.e. showModal() function):

@Ajax.ActionLink("Open", "Add", "Home", new {id = Model.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "modal", OnSuccess = "showModal()"})

此代码将我的表单(部分视图)加载到 div 中,并将其作为模式窗口打开.在表单提交 ActionResult 中,我只使用默认的 ModelState 对象来验证它,如果出现错误,我会返回包含模型错误的相同局部视图.除了以下情况外,这很好用:当模型不包含错误时,我想自动关闭模式窗口.我尝试了以下方法:

This code loads my form (partial view) into a div and opens it as a modal window. In the form submit ActionResult I just use the default ModelState object to validate it, and in case of an error I return the same partial view containing model errors. This works fine except for the following situation: when the model contains no errors I want to auto-close the modal window. I tried the following:

@using (Ajax.BeginForm("Save", "Home", new AjaxOptions {HttpMethod = "POST", UpdateTargetId = "modal", OnSuccess = "hideModal(); alert('Saved');"}))

但是,当模型包含错误时,Ajax 调用仍然有效,因此将调用 OnSuccess.我试图通过在局部视图中发送错误 HttpStatusCode 来解决这个问题,但是 div 没有使用新的 html 进行更新.我认为唯一的解决方案是发送一个包含 javascript 代码的局部视图,当模型不包含错误时关闭模式窗口,但我认为这个解决方案不是很整洁.还有其他想法吗?

However, when the model contains errors the Ajax call is still valid, so OnSuccess will be called. I tried to solve this by sending an error HttpStatusCode in the partial view, but then the div is not updated with the new html. I think the only solution is sending a partial view containing javascript code that closes the modal window when the model contains no errors, but this solution is not very neat in my opinion. Any other ideas?

推荐答案

我今天只需要做同样的事情.我想出的解决方案是在操作成功时返回一个属性设置为 true 的 JsonResult.在 AjaxOptions 的 OnSuccess 回调中,我检查了该属性并关闭了我的模式窗口.

I just had to do the same thing today. The solution I came up with was to return a JsonResult with a property set to true when the action succeeded. In the OnSuccess callback of the AjaxOptions I checked for the property and closed my modal window.

控制器方法

[HttpPost]
public ActionResult Hold(JobStatusNoteViewModel model)
{
    if (ModelState.IsValid)
    {
        //do work
        return Json(new {success = true});
    }

    return PartialView("JobStatusNote", model);
 }

局部视图

<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "JobStatusForm", OnSuccess = "closePopUp" })) { %>
<div id="JobStatusForm">
    <!-- Form -->
</div>
<% } %>  

<script>
function closePopUp(data) {
 if (data.success) {
     //close popup
   }
}
</script>

这篇关于关闭包含 ASP MVC Ajax 表单的模式窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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