2014-05-05 163 views
0

符號我想打一個URL這樣哈希(#)的URL

www.site.com/?q=house 

但是當我打開該網站,我得到

www.site.com/# 

JavaScript之後

window.location.hash = "q=house"; 

網址看起來像

www.site.com/#q=house 

散列來自哪裏?如何從url中刪除它?

我RouteConfig如果是重要的

public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 

使用MVC 5

回答

2

您設置散列,而不是查詢字符串。這就是爲什麼。

http://www.w3schools.com/jsref/prop_loc_hash.asp

你應該使用window.location.href像:

window.location.href = window.location.href + "?q=house"; 

如果您想更新您可以使用以下方法中的參數:

function UpdateQueryString(key, value, url) { 
    if (!url) url = window.location.href; 
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"); 

    if (re.test(url)) { 
     if (typeof value !== 'undefined' && value !== null) 
      return url.replace(re, '$1' + key + "=" + value + '$2$3'); 
     else { 
      var hash = url.split('#'); 
      url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, ''); 
      if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
       url += '#' + hash[1]; 
      return url; 
     } 
    } 
    else { 
     if (typeof value !== 'undefined' && value !== null) { 
      var separator = url.indexOf('?') !== -1 ? '&' : '?', 
       hash = url.split('#'); 
      url = hash[0] + separator + key + '=' + value; 
      if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
       url += '#' + hash[1]; 
      return url; 
     } 
     else 
      return url; 
    } 
} 

來源:add or update query string parameter