Home > DeveloperSection > Blogs > Optimizing URL Generation in ASP.NET MVC

Optimizing URL Generation in ASP.NET MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
0 Comment(s)
 6259  View(s)
Rate this:

Optimizing URL Generation in ASP.NET MVC

URL generation is particularly important for ASP.NET MVC because it uses a routing engine to map URLs to code. If we hard code a URL than we lose the ability to later vary our routing scheme.

ASP.NET MVC framework provides the following methods to generate URL. These methods help to optimized ASP.NET MVC application.

1.       Html.ActionLink()

2.       Html.RouteLink()

3.       Url.Action()

4.       Url.RouteUrl()

Html.ActionLink()

Html.Actionlink method is an easiest way to render an HTML link. In MVC, the Html.ActionLink()  does not link to a view. It creates a link to a controller action.

Syntax: Razor

@Html.ActionLink("Description", "Action Name")                                 

Syntax:ASPX

<%=Html.ActionLink("Description ", " Action Name ")%>

Example:

@Html.ActionLink("Go Back", "Index")

Html.RouteLink()

The RouteLink method renders an element that links to a URL, which can resolve to an action method, a file, a folder, or some other resource.

Syntax

@Html.RouteLink(HtmlHelper, String, Object)

RouteLink returns an anchor element (an element) that contains the virtual path of the specified action.

Html.RouteLink() is equivalent to Html.ActionLink(). You can see below line of code.

<%= Html.RouteLink("Click for Check", new {controller= "Home", action= "Index"}) %>

It is similar to as <a> tag in Html

<a href="/Home/Index">Click for Check</a>

Note:

ActionLink will generate the URL to get to an action using the first matching route by action name.

RouteLink will generate the URL to a specific route determined either by name or route values.

Url.Action()

It generates a fully qualified URL to an action method.

Example

@*link to a controller*@

@Url.Action("Home");

@*link to an action *@

@Url.Action("Home", "Index");

@*link to an action and send parameters*@

@Url.Action("Edit", "Product", new RouteValueDictionary(new { id = product.Id }));

The URL that is returned by this method has a format like the following:

\Home\About

If special characters in the URL must be encoded, use the Encode method. For the previous example, the Encode method returns the following URL:

%2fHome%2fAbout

Url.RouteUrl()

It generates a fully qualified URL for the specified route values by using a route name and the protocol to use.

Url.RouteUrl method is similar to Url.Action method with some difference that is; Url.Action() is MVC specific (it uses controller and action names), while RouteUrl() is generic is and can be used without MVC (you can have routing in WebForms).

Example

@Url.Action("About", "Home", null, Request.Url.Scheme)

@Url.RouteUrl("Default", new { Action = "About" }, Request.Url.Scheme)


Don't want to miss updates? Please click the below button!

Follow MindStick