Showing posts with label How to work Area in MVC || RAJESH GAMI. Show all posts
Showing posts with label How to work Area in MVC || RAJESH GAMI. Show all posts

How to work Area in MVC || RAJESH GAMI






Working with Area

Basically, Area are used to better manage large projects. For example, you might have an e-commerce application with admins, shops, billing sections, and admins managing back-end tasks such as creating categories, catalogs, prices, and so on. The store is an end-user portal for searching, which you add to your cart selection and where billing is done and delivery is managed.
 
As you can see, each of these sections is functionally very large and can be easily divided into sections. Let's see how to start from the Area.

Add an area in a MVC project

1. In the new MVC4 application, right-click on the project and select Add> Area

add-area

2. Name the Area ‘Admin’

3. This will create an Areas folder  with the following hierarchy added to your project

new-area-folder-hierarchy

4. AdminAreaRegistration.cs file. The generated class looks like this

public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
  get
  {
   return "Admin";
  }
}
public override void RegisterArea(AreaRegistrationContext context)
{
  context.MapRoute(
   "Admin_default",
   "Admin/{controller}/{action}/{id}",
   new { action = "Index", id = UrlParameter.Optional }
   );
}
}

As you can see from the class, it derives from the AreaRegistration class and overrides the AreaName  and  RegisterArea properties. 

a. AreaName returns the name you specified when you created the area. 

b. RegisterArea registers a new route for an area that begins with "Admin" (the name of the area) by calling the MapRoute method of the context. 

5. Next, let's open Global.asax and check the order of the routes. Note that AreaRegistration.RegisterAllAreas () is called before RouteConfig.RegisterRoutes (). This basically means  that the above route is registered before the default ASP.NET root is installed. This is important because you can call / HomeController / Index / and / Admin / HomeController / Index. If / HomeController / Index is registered first, navigation to / Admin / HomeController / Index will be redirected to the wrong controller class.


protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}

Now that we've added a new area, let's add a controller and a view. Also call the  controller HomeController in the new area to test the routing. 

add-controller

Next, add a new view named Index to the Areas \ Admin \ View \ Home folder, add _ViewStart.cshtml to the Areas \ Admin \ View \ folder, and add the Areas \ Admin \ View \ Shared folder. Add _Layout.cshtml. .. 

adding-views

@{
    ViewBag.Title = "Index";
}

<h2>Areas\Home\Index</h2>
Listing 3 Index.cshtml

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Listing 4 _ViewStart.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Admin Area</title>
</head>
<body>
<h1>Admin Area</h1>
<div>
  @RenderBody()
</div>
</body>
</html>

Listing 5 _Layout.cshtml

 Now let's run the application. Before you reach the home page, it will be the next YSoD (Yellow Screen of Death).

multiple-controller-ysod

Don't you like the redundancy of exceptions? In plain language, this means: If you  have two controllers named HomeController, you need to specify their namespace when you register the route.

The AreaRegistrationContext is said to have used the namespace when registering the route with the RegisterArea method  we saw earlier. This leaves a default route registration with no namespace defined. Go to App_Start \ RouteConfig.cs and add the Namespaces parameter to your MapRoute method call. Pass the MvcAreasDemo.Controllers namespace as a parameter of the default HomeController.

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 },
   // add the explicit namespaces param when using Areas
   namespaces: new [] { "MvcAreasDemo.Controllers" }
);
}

  

Default MVC launch page

default-view-one-aread

Now when you go to the admin / home URL, you'll see that the home controller in the admin panel is working. 

Adding another Area

Now that the new scope has been added  and is working fine, how can I tell if the second scope is causing a  routing conflict? Now, as mentioned earlier, the AreaRegistrationContext internally passes the NameSpace to the root configuration. Therefore, multiple areas registered via the AreaRegistrationContext do not cause any problems. For your safety, add another scope called Store and add a HomeController  (do not copy from the admin scope or create a subclass between the admin scope and the store scope). You can copy the view and update it accordingly. 
Run the  application and go to all  three HomeControllers to view the pages individually.

 default-view-two-areas

Conclusion

In summary, sections are a useful configuration when trying to build a large front-end system with well-separated functional sections. The only problem is that controllers with the same name in scope must have different namespaces, and the default route (if used)  explicitly provides namespace parameters during controller configuration. That's what you need to do.


Set route as shown below into RouteConfig.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CableSoft
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new {area="Admin",controller = "Login", action = "Index", id = UrlParameter.Optional }
            ).DataTokens.Add("area""Admin");
        }
    }
}

RAJESH GAMI - Blog

Digital Signature Pad in Angular | RAJESH GAMI

  What is Signature Pad? Signature Pad could be a JavaScript library for drawing fancy signatures. It supports HTML5 canvas and uses variabl...