views:

67

answers:

1

One of the great things about ASP.NET MVC is the routing engine. I love to generate my urls and not having anything break when I change the routes.

However, I'm not sure how I can apply this mechanism on the client side.

Let's imagine a common scenario where I have two dropdown lists and the content of the second list depends on the selected item in the first list. I want to load the items of the second list asynchronously, when the selection in the first list changes.

The URL, using the default route, could look like this : /Cars/GetModelsForBrand/Honda

Easy enough...

var url = '/Cars/GetModelsForBrand/' + $("#brands").val();

What if I change the routing and the url becomes : /Honda/GetModels

I just broke my code in an non-obvious way.

Is there any way to generate urls from the client side ?

+2  A: 

We had a similar scenario and solved it by generating a link to the action and then appending our parameters to it later. We also had a case where we were unsure of action and wanted to set it at client time. In this case we we generated a link to Index and did a replace on client side.

By generate link, I mean using the Html.ActionLink helper method

Russell Steen
Do you mean like this?var url = '<%= Html.BuildUrlFromExpression<CarsController>(x => x.GetModelsForBrand("[BRANDNAME]")) %>';var brandUrl = url.replace('\[BRANDNAME\]', $("#brands").val());Not too clean, but I guess it could do the job.
David Thibault
Yes, that's what I mean. I'm not sure what string replacement speed is in java and if you have a lot of these you might want to find a better way.
Russell Steen
+1 on getting rid of magic strings
mxmissile