Having the ability to use URL mapping rules to handle both incoming and outgoing URL scenarios adds a lot of flexibility to application code.
In the previous MVC tutorial you learned how to map incoming URLs to specific actions in controllers ( ASP.NET MVC Routing ).
Now I'll show you how to create an outgoing URL from your view so you can call
different actions from various controllers.
To do this it's best to use html helpers from HtmlHelper class that render for you html controls. These methods usually return string with an html code.
The easiest way to create a link in MVC 3.0 is to use Html.ActionLink or
Url.Action method:
Html.ActionLink
Html.ActionLink renders a link in a view file. There are few overloaded
methods where you can specify attributes such as:
- linkText - actual text of the link that will be displayed on your web site
- actionName - a name of concrete method that will be called from a controller
- controllerName - name of the controller
- protocol - the protocol that will be used (e.g. http)
- hostName - the host name of the link
- htmlAttributes - set of html attributes that will be added to a link
So let's see a couple of examples. Firstly take a look at the following code:
This method renders the following link: <a
href="/Countries/Action">Click!</a>, so it calls a method named "Action" from
a "CountriesController" file.
You might want to call a method from a controller with an argument. To do this use
the
following code:
The last argument of this function is null - it's a htmlAttributes object but
we don't want to render any attributes so we leave this as "null". This will
render the following link: <a href="/Countries/Show?count=3">Click me!</a>
Url.Action
This method generates raw URL address without a link so you can use it in
different ways. It's very similar to the Html.ActionLink method so there should
not be problem with using it. Take a look at the following code:
This will generate URL like: /Controller/Action.
In order to call a method with
an argument use the following code:
And the result will be: /Controller/Action?arg=4
Summing up ASP.NET MVC 3 has convenient methods to create outgoing URLs and
also to handle incoming ones.