将JialResult ActionMethod中的PartialView返回到ajaxpost并将PartialView显示为Modal弹出窗口

我试图将部分视图或任何其他视图从操作方法返回到ajaxpost。 我想从ajax成功函数或以其可能的方式显示内容ParitalView作为Jquery Modal弹出窗口。

带有注册表单的“MyRegistrationView”下面提到了表单提交按钮上的ajax post call。

$.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调用使用如下的action方法进入名为“MyRegistrationController”的Controller。

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

现在

  1. 如何在ajax的’Success’function中找回’_ShowSuccessfulModalPartial’的’内容’,并显示当Modal弹出同一个注册页面时。
  2. 如果我想返回/重定向到其他视图,如果我有JsonResult作为我的ActionMethod的返回类型,我该怎么办呢。
  3. 我如何将注册过程中的ModalErrors发送回我的视图并在ValidationSummary下显示它们。

(注意:如果我不使用JsonResult作为返回类型,我会得到ajax’parseerror’意外的令牌<)

您可以返回部分视图而不是json。

在你的主视图中,你应该像这样添加对话框html(假设你正在使用jQueryUI):

 

确保初始化对话框。

 $(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 } }); 

希望这可以帮助。