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();
});
});
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();
});
});
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" ) %>' );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With