Skip to content Skip to sidebar Skip to footer

Building Relative URLs For An MVC App With JavaScript

I'm having trouble getting C# and JavaScript/jQuery to play nice here. I have a knockout view model, plain old javascript object... one of its property/methods fires off an .ajax()

Solution 1:

The way we do this in my MVC 3 project is to include the following in the Master Layout:

<script type="text/javascript">
    var baseSiteURL = '@Url.Content("~/")';
</script>

Then you just prepend that to your URLs in the JavaScript.

Which in your sample would read:

url: baseSiteURL + 'vendors/' + viewModel.count() + '/' + viewModel.filterText()

Solution 2:

One possibility is to send those javascript values as request parameters:

$.ajax({
    url: '@Url.Action("vendors")',
    data: { count: viewModel.count(), filter: viewModel.filterText() },
    dataType: 'json',
    success: function (data) {
        viewModel.vendors(data);
    }
});

Of course this implies that you are using default routes and the parameters will simply be sent to the server either as query string parameters (if you are using GET) or as part of the POST request body. In both cases you will fetch them on the server the same way:

public ActionResult Vendors(int count, string filter)
{
    ...
}

Another possibility, if you absolutely insist on having some custom routes for your AJAX requests, would be to use a simple string replace:

var url = '@Url.Action("vendors", new { count = "__count__", filter = "__filterText__" })';
url = url.replace('__count__', viewModel.count())
         .replace('__filter__', viewModel.filterText());
$.ajax({
    url: url,
    dataType: 'json',
    success: function (data) {
        viewModel.vendors(data);
    }
});

Solution 3:

Darin's answer is the most solid, but it requires sending data using query string params on the ajax call.

To avoid that, I simply wrapped the @Url.Action() method in quotes and appended the javascript values as I intended.

url: "@Url.Action("Vendors", "Home")/" + viewModel.count() + "/" + viewModel.filterText(),

Ultimately this produced the best results as it lets me keep a very clean url... Request.ApplicationPath seemed too hackish and can technically be null... @Url.Content() is intended for static "content" paths (ex. images, scripts)... etc.


Post a Comment for "Building Relative URLs For An MVC App With JavaScript"