当控制器返回时,从javascript打开新选项卡中的视图

时间:2017-07-26 07:15:36

标签: javascript jquery asp.net-mvc

我需要在控制器成功后打开一个新选项卡,控制器返回一个View

这是我的方法,但它不起作用:

function modify(){

  var1= someDataFromDOM;
  var2= anotherDataFromDOM;

  $.ajax({
    method: 'POST',
    url: '@Url.Action("ModifyObject", "ControllerName")',
    data: {id: var1, status: var2},
    success: function (data){
       var newTab = window.open("", "_blank", "",  true);
       newTab.document.body.innerHTML = data;
    }
  });
}

在控制器上

[HttpPost]
public ActionResult ModifyObject(int id, string status)
{
   ViewModelA model = new ViewModelA();
   model = bd.GetModelA(id, status);
   return View("ModifyObject", model);
}

控制器正确返回视图,但newTab变量具有空值

欢迎任何帮助

1 个答案:

答案 0 :(得分:3)

I think the problem is with the javascript window.open(). This function is blocked by browsers except user events. See herehere

以下是针对您的目的的解决方法,我已经过测试;

<input type="button" hidden="hidden" id="hack" />

$(function () {

    var var2 = "test";
    var var1 = 1;
    var htmlData;
    var win;

    $.ajax({
        method: 'POST',
        url: '@Url.Action("ModifyObject", "Controller")',
        data: { id: var1, status: var2 },
        success: function (data) {
            htmlData = data;
            $("#hack").trigger("click");
        }
    });

    $("#hack").on("click", function () {
        win = window.open("", "_blank");
        win.document.body.innerHTML = htmlData;

    });
});

但是,打开这样的新标签可能不是一个好方法。 你的modify()做了什么,但我不会使用ajax来打开新窗口,我会尝试用下面的代替它,请检查here

Html.ActionLink("LinkText", "ModifyObject", "ControllerName", new { Id = "param1", Status = "param2" }, new { target = "_blank" });

<强>更新

根据您的评论尝试此操作;

function modify()
{
    var grid = $("#datagrid").data("kendoGrid");
    var row = grid.getSelectedRow(); 

    var win = window.open("","_blank")
    var var1 = row.fieldID;
    var var2 = row.fieldStatus;
    var url = '@Url.Action("ModifyObject", "ControllerName")' + '?id=' + var1 + '&status=' + var2;
    win.location = url;
}