Introduction
In this article, we are going to explore different ways of URL creation in MVC and different fundamental concepts of MVC.
So let's get started with MVC fundamentals.
We have two different approaches available while creating an URL in MVC framework.
- ActionLink
- Raw HTML
Question - Which approach is best for URL creation?
Answer
Action LInk in the background queries the routing engine whenever the URL associated with the given controllers ACTION. Sometimes we do have Custom URLs associated with an action, and we require to change that URL in future. For this scenario actionLink will pick up the latest URL, you don't need to make any changes.
On the other hand, if you are using raw HTML, you need to update your links when URLs changed.
As a good programmer, we should always avoid changing URLs as URLs are the public contract of your app and can be referenced by other apps, and many times users bookmark the URLs. If you change them, all these bookmarks and references will be broken.
In the end, the decision is up to the programmer's choice, no hard and fast rule here.
Again, the simplest way is using raw HTML
1: Raw HTML
Example,
<a href = "Courses/Index"> View Course</a>
2: ActionLink
Below is the example of using ActionLink for URL creation.
@HTML.ActionLink("View Courses","Index","Courses")
If the targeted action needs a parameter we can make use of an anonymous object to pass the parameter values.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1})
This will generate a link as - courses/index/1
This method doesn't generate the link for a reason, we need to pass another argument to ActionLink. This argument can be null or an anonymous object to render any additional HTML attribute.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1}, null)
We have different HTML helpers available in MVC

Cheers
Join the conversation! Your thoughts help the community grow.