tags:

views:

1157

answers:

2

Hi, 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();
    });
});
+3  A: 

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" ) %>' );
});
tvanfosson
Apologies. I forgot to mention that this script is contained in a script library and not on the page itself.
Rake36
Updated my answer with a work around.
tvanfosson
Thanks. From a style point of view, I always try to completely remove embedded JS from my web pages. I like your solution though and I'll see if I can't use it come up with something I feel more comfortable with. I'm also a prototype.js user learning jQuery - so not aware of all the possibilities available.
Rake36
+1 Nice, just used this logic on a site i'm working on. Thanks for the post.
Alexander
A: 

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