MVC: How to change URL address in browser based on the AJAX request for the page?

1.5k Views Asked by At

I have an AJAX request on my MVC page:

@Ajax.ActionLink("Link","Index","Page1",new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId= "mainAjax", LoadingElementId="loader", OnComplete="ChangeUrl();" })

When clicking on the link, the page is loaded with the correct content, however, URL is not changed.

When clicking on the Link, the address bar should have http://localhost:1111/Link address.

What needs to be done to update the URL with the correct address of the requested page?

1

There are 1 best solutions below

0
saeid mohammad hashem On

You can use jquery binding on click event. for sample So you could add a class attribute to your links as follows;

@Ajax.ActionLink("Link Title", "ActionName", "Controller", new { @class = "menuItems" })

The add your click event;

$(document).ready(function () {
          $(".menuItems").click(function() {
            var href = $(this).attr("href");
            if (href.indexOf("javascript") >= 0)
                return;
            history.pushState(null, $(this).html, href);
        });
    });

you must attend to href parameter that passing to pushState function. this URL argument to pushState should be relative to the current page, or or an absolute URL in your own domain. You can't push state cross-domain - it would be a major security flaw. if URL argument is not correct, you get this error "Uncaught SecurityError: Failed to execute 'pushState' on 'History': A history state object with URL".