Saturday, 10 August 2013

Best Way to reuse code inside my Controller action method

Best Way to reuse code inside my Controller action method

I have certain code with in the same controller class that looks almost
the same, such as setting viewbags to populate all the drop down lists,
the same code applies in my Post and get Create and Edit action methods.
So I have created a private method at the end of my controller class as
follow:-
private void populateViewBags() {
string controllerName = RouteData.Values["controller"].ToString();
ViewBag.PossibleDataCenters = repository.AllDataCenter().OrderBy(a =>
a.Name).ToList();
ViewBag.PossibleZones = repository.AllZone().OrderBy(a => a.Name).ToList();
List<string> s = new List<string>();
s.Add(controllerName.ToLower());
ViewBag.Products = repository.GetProducts(s).OrderBy(a =>
a.COMPONENTNAME).ToList();
ViewBag.Sites = repository.GetSDOrg().OrderBy(a => a.NAME).ToList();
ViewBag.Customers = repository.FindAccountDefinition(null).ToList();
}
And I am calling this method inside my action method. So is it the right
way to re-use the code? Thanks

No comments:

Post a Comment