dina
dina

Reputation: 111

Open a view in new tab from javascript when controller returns

I need to open a new tab after the controller success, the controller returns a View

This is my approach but it doesn't work:

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

On the controller

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

The controller returns the view correctly but the newTab variable has null value

Any help will be welcome

Upvotes: 1

Views: 9607

Answers (1)

ibubi
ibubi

Reputation: 2539

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

Below is a workaround for your purposes, I have tested;

<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;

    });
});

However, opening a new tab like this may not be a good approach. It is not apperant what your modify() does, but I would not use ajax to open a new window, I would try to replace it with the below instead, please check here

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

Update

Try this as per your comment;

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;
}

Upvotes: 4

Related Questions