Tuesday 8 January 2013

ASP.NET MVC Overview

Model-View-Controller is an architectural pattern used to separate an application into three main aspects:

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 ASP.NET MVC Framework implements the MVC pattern that’s suitable for web applications.

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.

Example: http://mvc-demo.com/Home/Index/100/ABC/XYZ
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:

  • 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


9 comments:

  1. for ict 99 26 January 2016 at 11:54

    .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

    ASP.NET MVC Training | MVC Online Training | MVC Training | ASP.NET MVC Training in Chennai | ASP.NET MVC 6 Training | Dot Net Training in Chennai

    Reply Delete
  2. John 20 July 2017 at 11:55

    Thanks for sharing useful information. I am giving best MVC online training in Hyderabad


    best asp.net with MVC online training
    asp.net with MVC online training
    online asp.net with MVC training
    asp.net with MVC

    Reply Delete
  3. Unknown 20 October 2017 at 11:53

    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.

    Reply Delete
  4. rmouniak 25 June 2018 at 17:20

    Thank you for your guide to with upgrade information.
    .Net Online Course Hyderabad

    Reply Delete
  5. gowsalya 31 December 2018 at 10:50

    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! 
    python Training institute in Pune
    python Training institute in Chennai
    python Training institute in Bangalore

    Reply Delete
  6. priya 18 January 2019 at 12:03

    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!
    Data 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

    Reply Delete
  7. nisha 1 June 2020 at 11:56

    The Blog is really very Impressive. every Concept should be very neatly arranged and the concepts are explained very uniquely.

    Data 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

    Reply Delete
  8. Jayalakshmi 11 June 2020 at 23:55

    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.

    Dot 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




    Reply Delete
  9. praveen 1 September 2020 at 18:28

    You have shared useful and important script with us. Keep updating.
    java 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

    Reply Delete
Add comment

Newer Post Older Post Home

4617作文网淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻让美丽中国“从细节出发”清明节放假3天调休1天男子给前妻转账 现任妻子起诉要回网友建议重庆地铁不准乘客携带菜筐月嫂回应掌掴婴儿是在赶虫子重庆警方辟谣“男子杀人焚尸”国产伟哥去年销售近13亿新的一天从800个哈欠开始男孩疑遭霸凌 家长讨说法被踢出群高中生被打伤下体休学 邯郸通报男子持台球杆殴打2名女店员被抓19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警两大学生合买彩票中奖一人不认账德国打算提及普京时仅用姓名山西省委原副书记商黎光被逮捕武汉大学樱花即将进入盛花期今日春分张家界的山上“长”满了韩国人?特朗普谈“凯特王妃P图照”王树国3次鞠躬告别西交大师生白宫:哈马斯三号人物被杀代拍被何赛飞拿着魔杖追着打315晚会后胖东来又人满为患了房客欠租失踪 房东直发愁倪萍分享减重40斤方法“重生之我在北大当嫡校长”槽头肉企业被曝光前生意红火手机成瘾是影响睡眠质量重要因素考生莫言也上北大硕士复试名单了妈妈回应孩子在校撞护栏坠楼网友洛杉矶偶遇贾玲呼北高速交通事故已致14人死亡西双版纳热带植物园回应蜉蝣大爆发男孩8年未见母亲被告知被遗忘张立群任西安交通大学校长恒大被罚41.75亿到底怎么缴沈阳一轿车冲入人行道致3死2伤奥运男篮美国塞尔维亚同组周杰伦一审败诉网易国标起草人:淀粉肠是低配版火腿肠外国人感慨凌晨的中国很安全男子被流浪猫绊倒 投喂者赔24万杨倩无缘巴黎奥运男子被猫抓伤后确诊“猫抓病”春分“立蛋”成功率更高?记者:伊万改变了国足氛围奥巴马现身唐宁街 黑色着装引猜测

4617作文网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化