ASP.NET MVC 6 Tutorial :: Clean up Controller Class in ASP.NET MVC

ASP.NET is used by millions of developers worldwide to build web apps. With each release, Microsoft changes ASP.NET for the better and version 5 with ASP.NET MVC 6 is no exception. Microsoft says that this upgrade makes “ASP.NET leaner, more modular, cross-platform, and cloud optimized.”

In this article, I will tell you about How to Clean up Controller Class in ASP.NET MVC 6. Here may be a tiny piece and the way i use some easy tricks to assist clean up my Controllers in ASP.NET MVC.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

publicclassMyController:Controller

{

publicMyEntitiesDb{get;set;}

protectedoverride voidOnActionExecuting(

ActionExecutingContext filterContext)

{

if(filterContext.IsChildAction)

return;

this.Db=newMyEntities();

base.OnActionExecuting(filterContext);

}

[HttpPost]

publicActionResult Index(FormCollection form)

{

stringsrch=form["Search"]??string.Empty;

returnRedirectToAction("Index",

new{search=srch});

}

protectedvoidAttachToDb(EntityObject obj,

boolsave=false,stringentityKeyField="Id")

{

obj.EntityKey=newEntityKey(

obj.ToPluralizedString(),entityKeyField,

obj.GetType().GetProperty("Id")

.GetValue(obj,null));

Db.Attach(obj);

Db.ObjectStateManager.ChangeObjectState(

obj,System.Data.EntityState.Modified);

if(save)Db.SaveChanges();

}

}

The first issue within the code is easy declaration of an EntityContext – this can be enforced directly, however might (and sometimes should) be implemented differently for dependency injection, however you get the thought. Here is wherever I conjointly prefer to include stuff that’s typically used and will be very important (and centralized) for an application like an output sort for web services (JSON, XML, etc.).

Next the OnActionExecuting is over-ridden and also the Context is initialized. Here is wherever you’ll be able to initialize the properties you set above.

The next methodology, the HttpPost Index method is simply an example of however often times you’ll be able to consolidate a normally used method. For this instance, it absolutely was from an application that had searches on all index pages. Rather than repeating this code in each controller, you’ll be able to simply place it here.

The final methodology has become terribly helpful. A use I often realize, is when taking in a large model when an ASP.NET MVC POST event, I will attach the model to the db generically with none further work

This method may be a bit confusing, however it’s merely attaching the new model to the db while not a db lookup. In my tables, I typically have a field ‘Id’ that houses the primary Key of every table, whether or not it’s an Int or Guid. This way, I will merely pass in whatever object i’m currently working with, and by using the pluralize method, and reflection, the method will find out that table to connect the model to – eliminating the requirement on behalf of me to try and do extra writing. or else, if i need to change the Key from ‘Id’, I will pass that in as well.

Now once I get a model being posted, it’s simple to deal with:

1

2

3

4

5

6

7

8

9

10

[HttpPost]

publicActionResult Edit(Widget model)

{

if(ModelState.IsValid)

{

AttachToDb(model,true);

//do stuff

}

else{/*do other stuff*/}

}

This avoids the need to take another trip to the db, change the properties on the object, then submit – streamlining the method very much and lowering plenty of code. This would be an example of however this is able to be done manually with the normal Controller class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

[HttpPost]

publicActionResult Edit(Widget model)

{

if(ModelState.IsValid)

{

MyEntities db=newMyEntities();

Widgetw=db.Widgets.Single(x=>x.Id==model.Id);

w.Name=model.Name;

w.Serial=model.Serial;

db.SaveChanges();

//do stuff

}

else{/*do other stuff*/}

}

Not a large difference once you are simply getting a pair of values, however you may see how a model with twenty or thirty fields are often block from 30+ lines to just 1 or 2.

HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24×7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality – beyond other hosting control panels – and ease of use, Plesk Control Panel is available only to HostForLIFE’s customers. They offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.

ASPDotNet5Hosting.com is designed to help ASP.NET beginners and experts. The site was founded in 2014 by Simon, Thomas, Elizabeth and Diandra, who are professional ASP.NET geeks. Our experts have been evaluating many hosting companies for many years. The business aims to provide people with better products at cost-effective prices.

ASPDotNet5Hosting.com researches and evaluates the Best, Cheap and Recommended Windows web hosting providers in the world. we've selected the highest performing hosting and compared their services. Our mission is to stay you informed regarding the advantages and disadvantages of the various providers and that we can continually evaluate hosts’ performance based on the reviews you post on our web site.