簡體   English   中英

如何在window.open方法中傳遞參數?

[英]How to pass parameter in window.open method?

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

C#控制器中的方法如下所示:

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

現在,當訪問C#方法時,我需要傳遞諸如名稱和日期之類的參數。 我怎樣才能做到這一點?

以以下格式將參數附加到URL:

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

如果您需要傳遞值數組,請對參數使用相同的名稱

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

所以您的網址看起來像

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


更新:

要在Action中接收它們,請聲明要傳遞給Action的參數。

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

閱讀ASP.NET MVC中的模型綁定

我找到了一種將參數傳遞到彈出窗口甚至從中檢索參數的更好方法:

在主頁中:

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

在彈出窗口中:

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

而已 !

這非常方便,因為:

  • 您不必在彈出窗口的URL中設置參數。
  • 沒有表格可以定義
  • 您甚至可以使用無限參數甚至對象。
  • 雙向:您可以傳遞參數,並且,如果需要,可以檢索新參數。
  • 非常容易實現。

玩得開心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM