Jemes
Jemes

Reputation: 407

Route Links - Url.Action

I'm trying to return my links so they display as /Area_1419.aspx/2/1.

I've managed to get that result in example 2 but I don't understand why it works, as I would exspect example 1 below to work.

I don't see how Example 2 knows to go to the Area_1419 controller?

Route

routes.MapRoute(
    "Area_1419 Section",
    "Area_1419.aspx/{section_ID}/{course_ID}",
    new { controller = "Home", action = "Index" }
);

Links Example 1

<a href='<%=Url.Action("Area_1419", 
   new { section_ID="2", course_ID="1" })%>'><img .../></a>

Returns: /Home.aspx/Area_1419?section_ID=2&course_ID=1

Links Example 2

<a href='<%=Url.Action("index", 
   new { section_ID="2", course_ID="1" })%>'><img .../></a>

Returns: /Area_1419.aspx/2/1

Upvotes: 0

Views: 6950

Answers (2)

d.popov
d.popov

Reputation: 4255

You can use Url.RouteUrl(), in your case

Url.RouteUrl("Area_1419 Section", new { controller = "Home", action = "Index", section_ID="2", course_ID="1"}

to be sure you use the correct route name, and get the correct URL no-matter-what.

Upvotes: 1

Arnis Lapsa
Arnis Lapsa

Reputation: 47587

Remember - URLs are detached from your controllers and their actions.

That means - even bizzare URL such as "trolololo/nomnomnom/1/2/3" might and might not call Home/Index or any other controller/action combo.

In your case - example 2 actually does not know how to go to Area_1419 controller.

Url.Action figures out url from these route details:

"Area_1419.aspx/{section_ID}/{course_ID}"

But link still will call Home controller Index action because of default route values:

new { controller = "Home", action = "Index" }


Assuming that you got Area_1419 controller with Index action, your route should look like:

routes.MapRoute(
    "Area_1419 Section",
    "Area_1419.aspx/{section_ID}/{course_ID}",
    new { controller = "Area_1419", action = "Index" } //changes here
);

This is what you are calling.

UrlHelper.Action Method (String, Object)

Generates a fully qualified URL to an action method by using the specified action name and route values.

This method overload does not try to figure out appropriate controller. It assumes that you know it (takes it out from current route values) and understands first string argument as an action name.

Try to use this one.

UrlHelper.Action Method (String, String, Object)
Generates a fully qualified URL to an action method by using the specified action name, controller name, and route values.

In your case:

Url.Action("Index","Area_1419", new { section_ID="2", course_ID="1" });

Upvotes: 2

Related Questions