2016-09-24 47 views
0

我想使用window.open(actionUrl) 打開新窗口actionUrl組成行動地址和url作爲參數。 所以最終actionUrl是: 「?/默認/詳細信息URL = http://www.someaddress.com?a1=1&a2=2&a3=3」 然而,在動作的URL我得到的是: 「http://www.someaddress.com?a1=1」 我不明白 「& A2 = 2 & A3 = 3」 的參數通過javascript發送具有參數到動作功能的url

下面是相關視圖的代碼:

<div> 
    <input type="button" value="test" id="btnTest" /> 
</div> 

<script> 
    var vurl = '@Url.Action("Details", "Default")'; 
    $(function() { 
     $("#btnTest").click(function() { 
      var url = "http://www.someaddress.com?a1=1&a2=2&a3=3"; 
      vurl = vurl + url; 
      window.open(vurl); 

     }); 
    }) 

</script> 

,這是控制器和動作

public class DefaultController : Controller 
{ 
    // GET: Default 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    // GET: Default/Details/5 
    public ActionResult Details(string url) 
    { 
     return View(); 
    } 
} 

回答

0

您需要使用encodeURIComponent函數的URL參數的值:

var actionUrl = '/Default/Details?url=' + encodeURIComponent('http://www.someaddress.com?a1=1&a2=2&a3=3'); 

&a2=2&a3=3部分實際上是/Default/Details URL,而不是http://www.someaddress.com一個組成部分。現在內部URL是URI編碼的,它應該可以工作。

確保使用雖然url參數時的值進行解碼,使用decodeURIComponent

var urlMatch = location.search.match(/url=(.*)&?/); 
if (urlMatch) { 
    var decodedUrl = decodeURIComponent(urlMatch[1]); 
    // do something with the decoded URL... 
} 

編輯

對於第一部分(URI編碼),並根據您的代碼,你應該這樣使用它:

<div> 
    <input type="button" value="test" id="btnTest" /> 
</div> 

<script> 
    var vurl = '@Url.Action("Details", "Default")'; 
    $(function() { 
     $("#btnTest").click(function() { 
      var url = "http://www.someaddress.com?a1=1&a2=2&a3=3"; 
      vurl = vurl + encodeURIComponent(url); 
      window.open(vurl); 

     }); 
    }) 

</script> 

至於ASP.NET部分和使用th e string url參數,我建議檢查以下帖子:using decodeURIComponent within asp.net因爲我不熟悉這個環境。

+0

謝謝, 使用encodeURIComponent解決了這個問題。 但是,我不明白何時以及爲什麼要使用decodeUriComponent – dan

+0

我想這取決於情況。通常當你編碼一個參數時,你需要在你想使用它時解碼它,否則你最終會得到不需要的編碼字符。例如,編碼的「url」值是'http%3A%2F%2Fwww.someaddress.com%3Fa1%3D1%26a2%3D2%26a3%3D3'這不再是有效的URL。你必須對它進行解碼才能獲得有效/可用的URL。但我猜ASP.NET本身處理URI編碼參數,所以你不必費心解碼部分 – Brunt