Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MVC jQuery relative path for window.location

I have a real simple problem, but can't seem to figure it out.

The following doesn't work because of the way MVC builds the URL (It includes all the route information). I want pathname to return the virtual directory path only.

All I'm doing is redirecting to a different route when a user selects an ID from a drop down list.

$(document).ready(function() {
    $('#TransactionIds').change(function() {
        document.location = window.location.pathname + "/CeuTransaction/Index/" + $('#TransactionIds').val();
    });
});
like image 244
Rake36 Avatar asked Jun 15 '09 14:06

Rake36


2 Answers

Here's what I ended up doing.

Added a hidden text field to page:

<input type="hidden" value="<%= Url.Content("~/CeuTransaction/Index/") %>" id="pathname" />

used the following in js script library:

// The following line enables jQuery intellisense
/// <reference path="jquery-1.3.2-vsdoc.js" />

$(document).ready(function() {
    $('#TransactionIds').change(function() {
        document.location = $('#pathname').val() + $('#TransactionIds').val();
    });
});
like image 31
Rake36 Avatar answered Sep 25 '22 17:09

Rake36


Use the UrlHelper to build the path. It will take into account the location of the application relative to the web server root.

$(document).ready(function() {
   $('#TransactionIds').change(function() {
       document.location = '<%= Url.Action( "Index", "CeuTransaction" ) %>'
                            + '/'
                            + $('#TransactionIds').val();
   });
});

Alternative: split into two parts so that the function can be included in a javascript library (still needs to be invoked from view or master). With a little bit of work you could make it a jQuery extension, too.

function redirectOnChange( selector, action )
{
   $(selector).change( function() {
       document.location = action + '/' + $(selector).val();
   });
}

In the view:

$(function() {
    redirectOnChange('#TransactionIds',
                     '<%= Url.Action( "Index", "CeuTransaction" ) %>' );
});
like image 119
tvanfosson Avatar answered Sep 23 '22 17:09

tvanfosson