Understand Asp.Net MVC request cycle
Lab 31 Implement User friendly URLs
Step 1 – Redefine RegisterRoutes method
Include additional routes in the RegisterRoutes method as follows.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Upload",
url: "Employee/BulkUpload",
defaults: new { controller = "BulkUpload", action = "Index" } );
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
}
As you can see now we have more than one route defined.
(Default Route is kept untouched.) Step 2 – Change URL references
Open AddNewLink.cshtml from “~/Views/Employee” folder and change BulkUpload link as follows.
<a href="/Employee/BulkUpload">BulkUpload</a>
Step 3 – Execute and Test
Execute the application and see the magic.
SUKESH MARLA 11 9
As you can see URL is no more in the form of “Controller/Action”. Rather it is more user friendly but output is same.
I recommend you to defines some more routes and try some more URLs.
Talk on Lab 31
Does earlier URL work now?
Yes, earlier URL will work too.
Now Index action in the BulkUploadController is accessible from two URLs 1. “http://localhost:8870/Employee/BulkUpload”
2. “http://localhost:8870/BulkUpload/Index”
What is “id” in default route?
We already spoke about it. It’s called Route Parameter. It can be used to get values via URL.
It’s a replacement for Query String.
What is the difference between Route Parameter and Query String?
Query String have size limitation whereas we can define any number of Route Parameters.
We cannot add constraints to Query String values but we can add constraints to Route Parameters.
Default Value for Route Parameter is possible whereas default value for Query String is not possible.
Query String makes URL cluttered whereas Route Parameter keep it clean.
How to apply constraints to Route Parameter?
It can be done with the help of regular expressions.
Example: look at the following route.
routes.MapRoute(
"MyRoute",
"Employee/{EmpId}",
new {controller=" Employee ", action="GetEmployeeById"}, new { EmpId = @"\d+" }
);
Action method will look like below.
SUKESH MARLA 12 0 public ActionResult GetEmployeeById(int EmpId)
{ ...
}
Now when someone make a request with URL “http://..../Employee/1” or “http://..../Employee/111”, action method will get executed but when someone make a request with URL
“http://..../Employee/Sukesh” he/she will get “Resource Not Found” Error.
Is it a required to keep parameter name in action method same as Route Parameter Name?
Basically a single Route pattern may contain one or more RouteParameters involved in it.
To identify each route parameter independently it is must to keep parameter name in action method same as Route Parameter Name.
Does sequence while defining custom routes matters?
Yes, it matters. If you remember UrlRoutingModule will take first matching route object.
In the above lab we have defined two routes. One custom route and one default route.
Now let say for an instance default route is defined first and custom route is defined second.
In this case when end user make a request with URL “http://.../Employee/BulkUpload” in the
comparison phase UrlRoutingModule finds that requested URL matches with the default route pattern and it will consider “Employee” as the controller name and “BulkUpload” as the action method name.
Hence sequence is very important while defining routes. Most generic route should be kept at the end.
Is there an easier way to define URL pattern for Action method?
We can use Attribute based routing for that.
Let’s try it.
Step 1 – Enable Attribute based routing.
In RegisterRoutes method keep following line after IgnoreRoute statement.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
...
Step 2 – Define route pattern for an action method
Simply attach Route attribute to Action method to Index action of EmployeeController as follows.
[Route("Employee/List")]
public ActionResult Index()
SUKESH MARLA 12 1 {
Step 3 - Execute and Test
Execute the application and complete login process.
As you can see, we have same output but with different more User Friendly URL.
Can we define Route Parameters with attribute based routing?
Yes, look at the following syntax.
[Route("Employee/List/{id}")]
public ActionResult Index (string id) { ... }
What about the constraints in this case?
It will be easier.
[Route("Employee/List/{id:int}")]
We can have following constraints 1. {x:alpha} – string validation 2. {x:bool} – Boolean validation 3. {x:datetime} – Date Time validation 4. {x:decimal} – Decimal validation
5. {x:double} – 64 bit float point value validation 6. {x:float} – 32 bit float point value validation 7. {x:guid} – GUID validation
8. {x:length(6)} –length validation
9. {x:length(1,20)} – Min and Max length validation 10. {x:long} – 64 int validation
11. {x:max(10)} – Max integer number validation 12. {x:maxlength(10)} – Max length validation 13. {x:min(10)} – Min Integer number validation 14. {x:minlength(10)} – Min length validation 15. {x:range(10,50)} – Integer range validation
16. {x:regex(SomeRegularExpression)} – Regular Expression validation What does IgnoreRoutes do in RegisterRoutes method?
IgnoreRoutes will be used when we don’t want to use routing for a particular extension.
SUKESH MARLA 12 2 As a part of MVC template following statement is already written in RegisterRoutes method.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
It means if end user make a request with an extension “.axd” then there won’t be any routing operation.
Request will directly reach to physical resource.
We can define our own IgnoreRoute Statement as well.
Conclusion
With Day 6 we have completed our sample MVC project. Hope you have enjoyed the complete series.
Wait!!! Where is Day 7?
Day 7 will be there my friends. In day 7 we will create a Single Page Application using MVC, jQuery and Ajax. It will be more fun and more challenge. Stay tuned
Your comments, Mails always motivates us do more. Put your thoughts and comments below or send mail to [email protected]
Connect us on Facebook, LinkedIn or twitter to stay updated about new releases.
For Offline Technical trainings in Mumbai visit StepByStepSchools.Net For Online Trainings visit JustCompile.com or www.Sukesh-Marla.com