Controllers In MVC By Sagar Jaybhay

In this article you will understand what Is Controllers In MVC and What is the use of Controller in Asp.Net MVC.









Controllers In MVC









In MVC the URLs are mapped to the Controllers action method so the question is how URLs are mapped to the Controllers action method? The answer for that ASP.NET routing. It is registering in Global.asax file.









Gloabl.asax File In MVC
Gloabl.asax File In MVC








The Registeroute method Is present in RouteConfig.cs file see below image,









RegisterRoute Method In MVC
RegisterRoute Method In MVC








Below is the RegisterRoute method in that class file.









public static void RegisterRoutes(RouteCollection routes)

routes.IgnoreRoute("resource.axd/*pathInfo");

routes.MapRoute(
name: "Default",
url: "controller/action/id",
defaults: new controller = "Home", action = "Index", id = UrlParameter.Optional
);

}








In the above code, you can see, the Default route is present it means
if you simply run the application then it will invoke this URL path the normal
path which you see after run application https://localhost:44374/.





This URL is the same as https://localhost:44374/Home/Index
this URL
is the same as the above URL. The controller is Home and action is Index.





So in the RegisterRoute method MapRoute method if see id is an optional parameter but if you pass and you need to access this you need to modify action method signature in controller and code looks like this below.









QueryString In MVC
QueryString In MVC








This is one way to get QueryString parameter from URL to action but you can also use our older way to access the parameters. Use the below method for that.










https://youtu.be/rIHCSIm87JM








public ActionResult Index(string id)

ViewBag.id = id;
ViewBag.name =Request.QueryString["name"];
return View();









Above id code for that, in above code we use Request.QuerySting method to access URL parameters and application works as expected.









QueryString In MVC 1
QueryString In MVC 1








In Register.Route method one more method









routes.IgnoreRoute("resource.axd/*pathInfo");








Which is used to ignore route path for the file whose extension .axd. It means that the request is not passed to the below MapRoute method and file directly get from this.














GitHub - https://github.com/Sagar-Jaybhay/MVC5






Comments

Popular posts from this blog

How to Start a YouTube Channel Free - Complete Guide

How Angular know which module is the startup module?

How to Start a YouTube Channel Free - Complete Guide