Model-View-Controller is an architectural pattern used to separate an application into three main aspects:
The
ASP.NET MVC Framework implements the MVC pattern that’s suitable for web applications.
Visual Studio MVC Project
Routing: The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. By default routes defined in “Global.asax” file method named “RegisterRoutes”. Method “RegisterRoutes” get called by “Application_Start” method when the application is first started.
RedirectToAction : Its used to call another action method using GET request
RedirectToRoute:
Each area represent a functional segment of the application. Area is very useful for large project. In area we can manage separate set of resources like Model/View/Controller based on segment/sub-applications/module. Area also helps developers to work together without colliding with one another work.
Area can be created in project after right click on project file and select area. area contain a mini project with model/view/controller folder with a area registration class file. For example if we create a area Admin than one file AdminAreaRegistration will create to manage route of the area. Method RegisterArea use to declare area route. This method get called once application start using "global.asax" file.
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
Routes.RegisterRoutes(context);
}
}
protected void Application_Start()
{
//This call RegisterArea methods of all class which derived from AreaRegistration class
AreaRegistration.RegisterAllAreas();
}
Area Route: Area route works same as normal route here we can use area as part of URL.
Example : @Html.ActionLink("Admin Area", "Index",new { area= "Admin" })
Other Posts: Controller and Actions | Filters | Views | Templates | Model Binding | Model Validation | Unobtrusive AJAX
Model: The model represents and
manipulates data of the application. It responds to the request from the view
and it also responds to instructions from the controller to update itself. A
class or set of classes that describe data and responsible for maintaining data.
View: The view represents an
interface to show to the user. Typically, this interface is rendered from the
model data triggered by a controller decision. Also view handles requests from
user and informs controller.
Controller: The controller is responsible
for responding to user input, performs interactions on the data model objects
and ultimately selects a view to render.
The main
advantages of ASP.Net MVC are:
- Full control over the rendered HTML.
- Clean separation of concerns.
- Test Driven Development (TDD).
- Powerful routing system.
- Built in ASP.Net platform.
- No View State/Post Back event and Page life Cycle.
Visual Studio MVC Project
We can create visual studio MVC project with Empty, Internet Application or Intranet Application templates. Empty template creates a relatively small number of files and directories, and gives us just the minimum structure on which to build. The Internet Application and Intranet Application templates fill out the project to give a more complete starting point, using different authentication mechanisms that are suited to Internet and intranet applications.
ASP.NET MVC project structure: Project structure of MVC is
almost similar for all templates. See table below for details:
Table 1: MVC 3 Project Items
File
or Folder
|
Description
|
Content
|
Put static
content like images and CSS.
|
Controllers
|
Put controller
classes
|
Models
|
Put model classes
|
Scripts
|
Put script
libraries
|
Views
|
Put views and
partial views
|
Views/Shared
|
Put layouts and
shared views
|
Global.asax
|
Global ASP.NET
application class use to register routing, set up any code to run on application
initialization or to handle unhandled exceptions etc.
|
Web.config
|
Configuration
files of application.
|
App_Data
|
Use to put data,
such as XML files or DB files etc.
|
bin
|
Assembly of MVC application
and other referenced assemblies.
|
Routing: The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. By default routes defined in “Global.asax” file method named “RegisterRoutes”. Method “RegisterRoutes” get called by “Application_Start” method when the application is first started.
Default snippet:
using System.Web.Routing;
public static void RegisterRoutes(RouteCollection
routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
// URL with parameters
new
{ controller = "Home", action = "Index", id = UrlParameter.Optional
}
);
}
protected void
Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
The parameter to “RegisterRoutes” method is the
value of the static “RouteTable.Routes” property, which is an instance of the
RouteCollection class.
URL Patterns: Each route contains a URL
pattern. If the
pattern matches the URL, then it is used by the routing system to process that
URL. By default MVC application create a default route as below.
routes.MapRoute(
"Default", // The name of the route to map.
"{controller}/{action}/{id}",
// The URL pattern for the route.
new { controller = "Home", action = "Index", id = UrlParameter.Optional
}
// An object that contains default route
values.
);
URL patterns will match only URLs with the specified
number of segments. A default value is applied when the URL doesn’t contain a
segment that can be matched to the value.
Here URL pattern is "{controller}/{action}/{id}", where
pattern have 3 segment with default value. First segment maps to controller
second with action and third one with id which is optional. Below is the table
to show how a URL will map to pattern.
Table 2 : URL Mapping
Number of Segments
|
URLs
|
Segment variables
|
0
|
http://mvc-demo.com/
|
Map to default value:
Controller = "Home", Action = "Index"
|
1
|
http://mvc-demo.com/Home
|
Controller = "Home", Action = "Index"
|
2
|
http://mvc-demo.com/Home/Index
|
Controller = "Home", Action = "Index"
|
3
|
http://mvc-demo.com/Home/Index/Hi
|
Controller = "Home", Action = "Index" , Id=
“Hi”
|
4
|
http://mvc-demo.com/Home/Index/Hi/XX
|
No match—too many segments
|
2
|
http://mvc-demo.com/Account/LogOn
|
Controller = "Account", Action = "LogOn"
|
2
|
http://mvc-demo.com/Account/Profile
|
Controller = " Account ", Action = "Profile"
|
Static URL Segments: We can also create patterns
that have static segments. Suppose we want to create URLs that are prefixed
with Classic:
http:// mvc-demo.com /Classic/Home/Index
We can do so by using a pattern like
routes.MapRoute("Classic",
"Classic/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional
}
);
Route Ordering: The MapRoute method adds a route to the end of the route
collection, which means that routes are generally applied in the order in which
we add them. The route system tries to match an incoming URL against the URL
pattern of the route that was defined first, and proceeds to the next route
only if there is no match. The routes are tried in sequence until a match is
found or the set of routes has been exhausted.
Note: As practice we must define
more specific routes first and generic/default routes later.
Accessing a Custom Segment Variable in an Action
Method:
RouteData.Values["id"] Or Action method Parameters
Defining Variable-Length Routes:
A URL pattern is to accept a variable number of
segments.
routes.MapRoute("CatchAll",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional
}
);
The first three segments are used to set values for
the controller, action, and id variables, respectively. If the URL contains
additional segments, they are all assigned to the catchall variable. There is
no upper limit to the number of segments that the URL pattern in this route
will match.
Here controller = Home, Action = Index, id = 100, catchall
= ABC/XYZ
Prioritizing Controllers by
Namespaces:
If we have two controllers with same name in
different namespaces and an incoming URL matches a route.Whenever this naming
clash happens, an error is reported because MVC Framework doesn’t know what to
do. To resolve this clash we can give preference to certain namespaces.
routes.MapRoute("CatchAll",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional
},
new[] { "MVCDemo.Controllers"}
);
The namespaces added to a route are given equal
priority. If we want
to give preference to a single controller in one namespace, but have all other
controllers resolved in another namespace, we need to create multiple routes.
Constraining Routes:
Using a Regular Expression:
routes.MapRoute("CatchAll",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional
},
new { controller = "^H.*"
},
new[] { "MVCDemo.Controllers"}
);
In this example, we have used a constraint with a
regular expression that matches URLs only where the value of the controller
variable begins with the letter H.
Route to a Set of Specific Values:
routes.MapRoute("CatchAll",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional
},
new { controller = "^H.*",
action="^Index$|^About$" },
new[] { "MVCDemo.Controllers"}
);
Here URLs will match only when the controller
variable begins with the letter H and the action variable is Index or About
Route Using HTTP Methods:
routes.MapRoute("CatchAll",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional
},
new { controller = "^H.*",
action="Index|About", httpMethod
= new HttpMethodConstraint("GET")},
new[] { "MVCDemo.Controllers"}
);
Bypassing the Routing System:
Prevent URLs, from being evaluated against our
routes. We do this by using the IgnoreRoute method of the RouteCollection
class.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
If the URL pattern passed to the IgnoreRoute method
matches, then no subsequent routes will be evaluated.
Generating Outgoing
URLs: There is number of ways to create
outgoing URLs in views and controller actions.
Generate URLs in View:
Html.ActionLink:
The straight forward way to generate an URL is to use ActionLink method of the HtmlHelper class. The ActionLink method generates an anchor element that contains the virtual path of the specified action. There are many overloaded versions of ActionLink method. Important parameters of ActionLink are:
The straight forward way to generate an URL is to use ActionLink method of the HtmlHelper class. The ActionLink method generates an anchor element that contains the virtual path of the specified action. There are many overloaded versions of ActionLink method. Important parameters of ActionLink are:
- linkText : The inner text of the anchor element.
- actionName : The name of the action.
- controllerName : The name of the controller.
- routeValues : An object that contains the parameters for a route. If value provided in routeValues does not correspond with a route parameter then values appended to the outgoing URL as the query string
- htmlAttributes : An object that contains the HTML attributes to set for the element. The “class” is a keyword that’s need to prefix with the “@” character.
@Html.ActionLink("Home",
"Index", "Home",
new { id = 100,para1=hi }, new { @class="clsLink"})
Html Output : <a href="/Home/Index/100?para1=hi">Home</a>
Url.Action:
The
Url.Action method works in the same way as the Html.ActionLink method, except that it generates
only the URL not anchor tag.
URL is: @Url.Action("Index ", " Home ", new { id = 100))
Html.RouteLink:
Another
way to generate URLs is to use the route name or route values.
@Html.RouteLink("Home", new {
controller = "Home", action =
"Index" })
Html.RouteUrl:
The
“UrlHelper.RouteUrl()” method returns an URL as a
string based on the route name or route values.
Generate URLs in Action Methods:
To generate a URL, same URL helper methods can use
in the action method like Url.Action and Url. RouteUrl.
RedirectToAction : Its used to call another action method using GET request
return
RedirectToAction("About", "Home");
The method works the same way as the “HtmlHelper.ActionLink()” or “UrlHelper.Action()“.
The “RedirectToAction()”
method is used to return an object of “RedirectToRouteResult“.
RedirectToRoute:
return
RedirectToRoute("Default", new { controller = "Home",
action = "About", id = "MyID" });
The method
works the same way as the “HtmlHelper.RouteLink()”
or “UrlHelper.RouteUrl()“.
The “RedirectToRoute()”
method is used to return an object of “RedirectToRouteResult“.
Areas:
ASP.Net MVC Framework support to use areas to break up the application into sub-applications.Each area represent a functional segment of the application. Area is very useful for large project. In area we can manage separate set of resources like Model/View/Controller based on segment/sub-applications/module. Area also helps developers to work together without colliding with one another work.
Area can be created in project after right click on project file and select area. area contain a mini project with model/view/controller folder with a area registration class file. For example if we create a area Admin than one file AdminAreaRegistration will create to manage route of the area. Method RegisterArea use to declare area route. This method get called once application start using "global.asax" file.
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
Routes.RegisterRoutes(context);
}
}
protected void Application_Start()
{
//This call RegisterArea methods of all class which derived from AreaRegistration class
AreaRegistration.RegisterAllAreas();
}
Area Route: Area route works same as normal route here we can use area as part of URL.
Example : @Html.ActionLink("Admin Area", "Index",new { area= "Admin" })
Other Posts: Controller and Actions | Filters | Views | Templates | Model Binding | Model Validation | Unobtrusive AJAX
.Net MVC Training | ASP.NET MVC Online Training | C# MVC Training | ASP.NET MVC Training in Chennai | Online ASP.NET MVC 6 Training | Dot Net Training in Chennai
ReplyDeleteASP.NET MVC Training | MVC Online Training | MVC Training | ASP.NET MVC Training in Chennai | ASP.NET MVC 6 Training | Dot Net Training in Chennai
Thanks for sharing useful information. I am giving best MVC online training in Hyderabad
ReplyDeletebest asp.net with MVC online training
asp.net with MVC online training
online asp.net with MVC training
asp.net with MVC
This is very good information for knowing the dotnet basic knowledage, Most of the institutes are providing asp.net with mvc online training institute in Ameerpet.
ReplyDeleteThank you for your guide to with upgrade information.
ReplyDelete.Net Online Course Hyderabad
I have picked cheery a lot of useful clothes outdated of this amazing blog. I’d love to return greater than and over again. Thanks!
ReplyDeletepython Training institute in Pune
python Training institute in Chennai
python Training institute in Bangalore
I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
ReplyDeleteData Science course in Indira nagar
Data Science course in marathahalli
Data Science Interview questions and answers
Data science training in tambaram
Data Science course in btm layout
Data science course in kalyan nagar
The Blog is really very Impressive. every Concept should be very neatly arranged and the concepts are explained very uniquely.
ReplyDeleteData Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery
Nice! you are sharing such helpful and easy to understandable blog. i have no words for say i just say thanks because it is helpful for me.
ReplyDeleteDot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery
You have shared useful and important script with us. Keep updating.
ReplyDeletejava training in chennai
java training in porur
aws training in chennai
aws training in porur
python training in chennai
python training in porur
selenium training in chennai
selenium training in porur