Close modal window containing ASP MVC Ajax form

一世执手 提交于 2019-12-03 14:42:45

问题


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

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

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?


回答1:


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.

Controller Method

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

    return PartialView("JobStatusNote", model);
 }

PartialView

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

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


来源:https://stackoverflow.com/questions/7431693/close-modal-window-containing-asp-mvc-ajax-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!