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.

public class MyController : Controller
{
    public MyEntities Db { get; set; }
    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        if (filterContext.IsChildAction)
            return;
        this.Db = new MyEntities();
        base.OnActionExecuting(filterContext);
    }
    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        string srch = form["Search"] ?? string.Empty;
        return RedirectToAction("Index",
            new { search = srch });
    }
    protected void AttachToDb(EntityObject obj,
        bool save = false, string entityKeyField = "Id")
    {
            obj.EntityKey = new EntityKey(
                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:
[HttpPost]
public ActionResult 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:

[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        MyEntities db = new MyEntities();
        Widget w = 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 ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.