dave317
dave317

Reputation: 774

Jquery or Javascript Redirect to Controller/Action

I have the following code which works on the first time around:

$("#CompDD").change(function () {
                //var parts = (window.location.pathname.split("/"));
                var ctrlName = '@ViewContext.RouteData.Values["Controller"].ToString()';
                var actnName = '@ViewContext.RouteData.Values["Action"].ToString()';
                var url = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
                //delete ctrlName;
               // delete actnName;
                //window.location = ($(location).attr('href') + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
                //window.location = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
                //$(location).attr('href', url);
                window.location.href = url;
                //alert(ctrlName + "\n" + actnName);
            });

However on subsequent changes of the drop down in question (#CompDD) it will add another controller/action to the end of the link, ex. it adds another "Patrons/Index" to the end of the existing "Patrons/Index", thenit adds the searchsrting variables etc.

Please excuse the comments and stuff on my code. How do i get Jquery (or javascript) to redirect without appending the controller name and action names over and over, or whats the best way to do this?

EDIT: Such an easy fix! I had to add the root slash to the URL string, example this worked:

var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());

Notice the forward slash at the start of the string I construct....Yikes!

Upvotes: 1

Views: 11278

Answers (2)

Mehar
Mehar

Reputation: 1

 function RedirectUrl() {
        if (domElement.textfor.val() == "Index") {
            window. location.href = E_host.AppVar.AppHost + "/Home/index";
        }
}

Upvotes: 0

Shyju
Shyju

Reputation: 218732

Use the Url.Action helper method to build path to action methods.

$("#CompDD").change(function () {

   var baseUrl="@Url.Action("Home","Search")";
   alert(baseUrl);
   // Now append your query string variables to baseUrl
   // Ex : baseUrl=baseUrl+"?searchString=testing"; 
   window.location.href=baseUrl;

});

Assuming you want to navigate to the search action method in Home controller.

Upvotes: 5

Related Questions