mvc tutorial for beginners - Part 79 Areas in asp net mvc

Database, Information Technology mvc tutorial for beginners

496 Lessons

Part 79 Areas in asp net mvc

Link for code samples used in the demo

Link for csharp,,, dotnet basics, mvc and sql server video tutorial playlists

When you create a new mvc application, the following folders are created with in the root directory.
1. Models
3. Controllers

This structure is fine for simple applications, but when your application gets big and complex, maintaining your Models, Views and Controllers can get complicated.

The structure of a complex mvc application can be very easily maintained using areas. So, in short areas are introduced in mvc 2, that allow us to breakdown a large complex application into a several small sections called areas. These areas can have their own set of
1. Models
3. Controllers
4. Routes

Let’s understand this with an example.

Let’s understand this with an example. Let’s say, we are building a Job Portal. It’s common for a typical job portal to have the following functional areas.
Employee Area – This functional area allows a job seeker to create their profile, upload resume, and perform job search.
Employer Area – This functional area allows a job provider to create employer profile, upload jobs, and search for suitable candidates.
Administrator Area – This functional area allows an administrator to configure the site and mantain.

To create an area in an MVC application
1. Right click on the project name in Solution Explorer and select Add =] Area
2. Provide a meaningful name. For example “Employee” and click Add

At this point, “Areas” folder will be created, and with in this, a folder for Emploee area will be added. You can add as many areas as you want.

In a similar fashion, add areas for Employer and Admin.

Notice that in each area folder (Employee, Employer and Admin), you have a set of Models, Views and Controllers folders. Also, there is “AreaRegistration.cs” file, which contains the code to register a route for the area.

Now navigate to Global.asax.cs file and notice Application_Start(). With in this method there is code to register all areas in your application.
protected void Application_Start()

At this point Add “HomeController” to the following areas. Notice that we can have a HomeController(Controller with the same) in Employee, Employer, Admin and MainArea.
1. Employee
2. Employer
3. Admin
4. Main Area

At this point, we have Index() action method in all of the HomeControllers.
public ActionResult Index()
return View();

Now Add Index view to all the areas. Copy and paste the following HTML in respective Index views.
Main Area: [h1]Main Area Index View[/h1]
Employee Area: [h1]Employee Area Index View[/h1]
Employer Area: [h1]Employer Area Index View[/h1]
Admin Area: [h1]Admin Area Index View[/h1]

At this point, build the application, and navigate to /MVCDemo. You will get an error.

To fix this change RegisterRoutes() method in RouteConfig.cs file in App_start folder. Notice that we are passing the namespace of the HomeController in the Main area using namespace parameter.
public static void RegisterRoutes(RouteCollection routes)

name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional },
namespaces: new [] { “MVCDemo.Controllers” }

Now, if you navigate to /MVCDemo/Employee, you will get an error – The resource cannot be found.

To fix this, change RegisterArea() area method in EmployeeAreaRegistration.cs file in Employee folder as shown below. Notice that we are setting HomeController as the default controller
public override void RegisterArea(AreaRegistrationContext context)
new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }

Navigating to http://localhost/MVCDemo/Employee may throw a compilation error related to System.Web.Optimization. If you get this error follow the steps below.
1. In Visual Studio, click Tools – Library PAckage Manager – Package Manager Console
2. In the Package Manager Console window, type the following command and press enter
Install-Package Microsoft.Web.Optimization -Pre

When we are building links using ActionLink() html helper to navigate between areas, we need to specify area name. once you do this, you will be able to navigate between areas when you click on the respective links.

    _layout _ViewStart .Net .net mvc entity framework @Ajax.ActionLink @RenderSection action action filter actionlink actionname actionresult Adding Advantages ajax ajaxhelper ajaxoptions Alert all checkboxes allowanonymous application areas argument array asp net mvc 5 delete confirmation asp net mvc hyperlink navigation asp net mvc link helper asp net mvc passing list to view asp net mvc required examples asp net mvc update view entity framework asp net mvc url and iis ASP.NET MVC mvc 4 create dropdownlist mvc 4 multi select list mvc 5 crud operations mvc access form collection mvc calendar date picker mvc confirm delete button mvc controller request.querystring mvc controller return string mvc convention over configuration mvc conventions mvc course mvc create hyperlink mvc create new view mvc crud operations mvc crud operations example mvc currency model binder mvc date picker helper mvc datepicker dateformat mvc datepicker example mvc datepicker format mvc datepicker not working mvc datetime datepicker mvc delete confirmation mvc dropdownlist data binding mvc dropdownlist from database mvc dropdownlist required mvc dto viewmodel mvc entity framework mvc example c# mvc example step by step mvc formcollection dropdownlist mvc formcollection empty mvc formcollection example mvc formcollection select mvc get data from database mvc hello world mvc html helper anchor mvc html.actionlink pass parameters mvc htmlhelper extension methods mvc insert to database mvc insert update delete mvc javascript confirm delete mvc jquery datepicker editorfor mvc jquery datepicker example mvc list view example mvc make dropdownlist required mvc model object mvc model validation mvc model validation example mvc multiple tables mvc pass model to view mvc razor foreach loop mvc required attribute mvc required field mvc required field validation mvc selectlist from database mvc tutorial mvc two tables mvc url mapping mvc version mvc view example mvc view foreach example mvc view from controller mvc view function mvc view validation mvc viewmodel example mvc viewmodel tutorial aspx assembly attack attribute Attributes Authorize auto auto generated autocomplete automatic avoid bad bellevue benefits between bi-directional bidirectional bind attribute bind mvc dropdownlist with database values black list brail built business objects C# c# mvc checkboxfor default checked c# mvc crud example c# mvc crud tutorial c# mvc entity framework tutorial c# mvc get checkbox value c# mvc object reference not set to an instance of an object cacheprofiles CDN CHECK checkbox checkbox list checkboxlist checking child actions childactiononly classes Client client-side code code blocks comments compare compareattribute compile time complete complex compress compression constant content control controller controller action controllers Convention create create mvc application create view Creating cross site scripting CRUD crud operations in mvc 5 crud operations in mvc 5 using entity framework currency format in mvc 4 current() custom custom errors custom view engine customize customizing Data data access Data Annotations data transfer object data- attributes database datatransferobject DataTypeAttribute date format in c# mvc date format in mvc razor date in mvc view datetime datetime in mvc model datetime picker delete Deleting delivery demo Detect determine diference difference differences disable disabled disadvantages display display data from two tables in mvc DisplayAttribute DisplayColumnAttribute DisplayFormatAttribute displaying data from multiple tables in mvc down download dropdownlist DropDownListFor dynamic views edit edit view editing edits employee department mvc enable encode encoding entity framework entity framework mvc entity framework mvc tutorial entity framework in mvc entity framework in mvc 4 entity framework in mvc tutorial errors escape example example of mvc with text box in c# exclude excluding explained explicit code nugget expression fallback feedback fiddler mvc post Fields files filters FIND find out first for beginners foreach in mvc razor view form format date in mvc controller FormCollection from functionality generate generating get request handleerror HandleErrorAttribute helpers hiddeninput HiddenInputAttribute how mvc works how does mvc know which view to return how iis process mvc request how mvc request is processed how to create mvc application in visual studio 2013 how to install mvc 3 how to install mvc 4 how to install mvc 4 in visual studio 2010 how-to html html helper html helper for textbox html helpers html.dropdownlist Html.DropDownListFor Html.Partial Html.RadioButton Html.RadioButtonFor Html.RenderPartial Html.TextBox Html.TextBoxFor HtmlHelper httpget httppost hyperlinks image images implement implementing include including index view insert install install mvc 3 installing mvc 3 installing mvc 4 interfaces is IsSectionDefined IsValid item javascript jquery jquery datepicker example in mvc key value pair keys layout links List Box listbox literal text loaded LoadingElementDuration LoadingElementI local locate location make a field required mvc method method mvc methods min.js Minification minified minify Model model binding model binding in mvc model metadata Model–view–controller models multiple multiple tables MVC mvc @model in view mvc 3 mvc 4 mvc 4 edit controller example mvc 4 edit view mvc 4 pass list from view to controller mvc access model in view mvc add validation dynamically mvc application mvc bind view to model mvc c# crud mvc checkboxfor checked by default mvc checkboxfor database mvc checkboxfor default value mvc checkboxfor get value mvc checkboxlist from database mvc combobox database selected value mvc combobox selected value mvc controller mvc create textbox mvc database example c# mvc dropdownlist database example mvc dropdownlist entity framework mvc dropdownlist entity framework database first mvc dropdownlist required validation mvc dropdownlist viewbag example mvc edit controller example mvc edit form example mvc edit httppost mvc edit page example mvc edit view drop down list mvc edit view example mvc editable drop down list mvc email hyperlink mvc employee example mvc entity framework c# tutorial mvc entity framework example mvc formcollection example mvc get all checked checkboxes mvc get selected items listbox mvc hide field in view mvc hide model property mvc htmlhelper best practices mvc htmlhelper hidden field mvc htmlhelper strongly typed mvc layout mvc listbox get selected items in controller mvc loop through checkboxes mvc mailto link mvc model mvc model attributes email mvc model class example mvc model example c# mvc model validation example mvc multiselect listbox mvc pages mvc partial class metadata mvc radio button database mvc radio button selected value mvc radiobuttonfor checked mvc razor edit form mvc razor edit view mvc razor html.dropdownlist example mvc razor mailto link mvc required attribute example mvc retrieve data from database mvc return view viewname mvc uihint example mvc update database from model mvc update example mvc update stored procedure mvc view search locations mvc2 mvc3 mvc3 html.actionlink parameters mvc4 Named sections navigation network new row nonaction not working Obtrusive OnBegin OnComplete OnFailure OnSuccess open in a new browser window Operations outputcache outputcacheattribute override own page pager pagination paging parameter types partial partial views partialviews pass model from controller to view mvc 4 pass model to view from controller pass viewmodel to controller c# populating post post request posted form values precompiling prevent preventing prevention progress project properties Public purpose RadioButtonFor radiobuttonlist range rangeattribute razor razor edit view dropdown razor multi select listbox read readonly ReadOnlyAttribute records Reflection regularexpression regularexpressionattribute remote RemoteAttribute render rendered RenderPartial request data requirehttps requirehttpsattribute restrict access result Routing rows runtime ScaffoldColumnAttribute Screen search search capability section sections select selected selected value selectedvalue selectlist selectlistitem selectors Server show side simple single sort Sorting Spark stringlength strongly typed html helpers strongly typed html helpers mvc 4 strongly typed views Structure summary support Syntax t4 templates templated helpers Templates text tag TextBox TextBoxFor the view index or its master was not found mvc 4 tryupdatemodel tutorial typeof uihint uihint attribute mvc uncheck Unintended updates Unobtrusive Update update view mvc updatemodel updating url Use use of using using fiddler with mvc using foreach in razor view validateinput validateinputattribute validation validation mvc validationsummary value values versions vewbag view view engines view index or its master was not found viewbag pass data from controller to view viewdata viewdata viewbag viewmodel ViewData.ModelMetadata ViewData.TemplateInfo viewmodel views viewstart visual visual studio create mvc application visual studio create mvc project what what is the use of shared folder in mvc white list Why Working working with multiple tables in mvc using entity framework xss