简体   繁体   中英

How to generate urls on the client side using ASP.NET MVC?

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM