3

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 ?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Constraints on parameters will also add some headache

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.