Question

I want to make an URL like this

www.site.com/?q=house

But when I open the site I get

www.site.com/#

after javascript

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

URL looks like

www.site.com/#q=house

Where the hash coming from? How to remove it from the url?

My RouteConfig if it is important

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

Using MVC 5.

Was it helpful?

Solution

you are setting the hash and not the query string. that's why.

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

You should use window.location.href like:

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

If you want to update a parameter you can use the following method:

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

Source: add or update query string parameter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top