返回PartialView从JsonResult ActionMethod回到阿贾克斯后并显示Par

2019-08-22 02:45发布

我试图返回回PartialView或操作方法的任何其他视图回到阿贾克斯后。 我想显示的内容ParitalView从无论怎样它可能成功的AJAX功能或一个jQuery模态弹出。

“MyRegistrationView”,上面有登记表已经下文提到的AJAX调用后对表单提交按钮。

 $.ajax({
            url: url,            //http://localhost/MyRegistration/RegisterUser
            type: 'POST',
            dataType: 'json',
            data: ko.toJSON(RegistrationInfoModel),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                //Do something
            },
            error: function (request, status, error) {
                //Do something
            }
        });

上述AJAX呼叫转到我的控制器命名为“MyRegistrationController”与下面的操作方法。

[HttpPost]
public JsonResult RegisterUser(RegistrationInfo model)
{
   //Register User
   ....
  if(successful)
  {
     return Json(new { data = PartialView("_ShowSuccessfulModalPartial") });   
  }

}

现在

  1. 我怎样才能回到阿贾克斯的“成功”功能“_ShowSuccessfulModalPartial”的“内容”,并表明,随着模态弹出一个相同的注册页面。
  2. 如果我想返回/重定向到其他一些观点我怎么能做到这一点,如果我有JsonResult作为我ActionMethod的返回类型。
  3. 我怎样才能的ValidationSummary下发回从注册流程回到我看来,ModalErrors并显示它们。

(注:如果我不使用JsonResult的返回类型我得到阿贾克斯parseerror“意外标记<)

Answer 1:

您可以返回的局部视图,而不是一个JSON。

在你的主视图,您shoudl添加这样的对话框HTML(assumming你使用jQueryUI的):

<div id="dialog-confirm" title="Your title">    
    <div id="dialog-content"></div>
</div>

确保你初始化对话框。

$(document).ready(function() {
    $("#dialog-confirm").dialog();
});

在控制器,你可能需要返回的局部视图:

[HttpPost]
public virtual ActionResult RegisterUser(RegistrationInfo model)
{
    var model = //Method to get a ViewModel for the partial view in case it's needed. 
    return PartialView("PartialViewName", model);
}

然后,当你做你的Ajax请求,你追加到对话框中的局部视图,然后显示它。

 $.ajax({
            url: url,          
            type: 'POST',
            dataType: 'json',
            data: ko.toJSON(RegistrationInfoModel),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                $("#dialog-content").empty();
                $("#dialog-content").html(result);
                $("#dialog-confirm").dialog("open");
            },
            error: function (request, status, error) {
                //Do something
            }
        });

希望这可以帮助。



文章来源: Return PartialView from JsonResult ActionMethod back to ajax post and display that PartialView as a Modal pop-up