简体   繁体   中英

How to pass parameter in window.open method?

I have the following method in JavaScript:

var string1 = "testing";
var date = "10/10/2012";

var win = window.open(BuildUrl(("report", "report"), "myreports",  
           "toolbar=0,statusbar=0,scrollbars=1,resizable=1,location=0");

function BuildUrl(controllerName, actionName) {        
    var TimeStamp = Number(new Date()); 
    var win = window.location;
    return win.protocol + "//" + win.host + "/" + controllerName + "/" + actionName + '?_=' + TimeStamp ;  
}

Method in C# controller looks like this:

public ActionResult report()
{               
    return View();
}

Now I need to pass parameters like name and date when the URL is accessed to the C# method. How can I do that?

Append the parameters to the URL in the following format:

<url>?param1=value1&param2=value...

If you need to pass an array of values then use the same name for the parameter

<url>?arr=value1&arr=value2...

So your URL would look like

domain.com/Controller/Report?name=xyz&date=20


Update:

To receive them in the Action, declare the parameters being passed to the Action.

public ActionResult Report(string name, DateTime date)
{
  ...
}

Read up on Model Binding in ASP.NET MVC

I found a better way to pass parameters to the popup window and even to retrieve parameters from it :

In the main page :

var popupwindow;
var sharedObject = {};

function openPopupWindow()
{
   // Define the datas you want to pass
   sharedObject.var1 = 
   sharedObject.var2 = 
   ...

   // Open the popup window
   window.open(URL_OF_POPUP_WINDOW, NAME_OF_POPUP_WINDOW, POPUP_WINDOW_STYLE_PROPERTIES);
   if (window.focus) { popupwindow.focus(); }
}

function closePopupWindow()
{
    popupwindow.close();

    // Retrieve the datas from the popup window
    = sharedObject.var1;
    = sharedObject.var2;
    ...
}

In the popup window :

var sharedObject = window.opener.sharedObject;

// function you have to to call to close the popup window
function myclose()
{
    //Define the parameters you want to pass to the main calling window
    sharedObject.var1 = 
    sharedObject.var2 = 
    ...
    window.opener.closePopupWindow();
}

That's it !

And this is very convenient because:

  • You have not to set parameters in the URL of the popup window.
  • No form to define
  • You can use illimited parameters even objects.
  • Bi-directionnal : you can pass parameters AND, if you want you, can retreive new parameters.
  • Very easy to implement.

Have Fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM