Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc best practice for common code

Tags:

asp.net-mvc

I have an MVC application. The following code is being used in multiple places within a controller and in multiple controllers. I would like to have this code in one place and call it from each location. What's the best way to do that in MVC?

The code below gets a row from the database and creates ViewData that can be read from the view. With webforms, I would create a public sub within a class and pass the year and month values. Is there a way this code could become part of the model?

var monthlyexpenseincome = (from vu_monthlyresult in dbBudget.vu_MonthlyResults
                            where vu_monthlyresult.Month == defaultmonth && vu_monthlyresult.Year == defaultyear
                            select vu_monthlyresult).Single();

var yearlyexpenseincome =  (from vu_yearlyresult in dbBudget.vu_YearlyResults
                            where vu_yearlyresult.Year == defaultyear
                            select vu_yearlyresult).Single();

ViewData["MonthlyExpenses"] = monthlyexpenseincome.Expenses;
ViewData["MonthlyIncome"] = monthlyexpenseincome.Income;
ViewData["MonthlyProfit"] = monthlyexpenseincome.Income - monthlyexpenseincome.Expenses;
like image 822
Matt Ellenburg Avatar asked Feb 27 '26 21:02

Matt Ellenburg


1 Answers

Generally, If you have common code across multiple controllers, you can create another class which inherits from Controller and keep your methods there and let your indidual Controlellers inherit this new class

public class BaseController : Controller
{
   protected string GetThatInfo()
   {
      //do your magic logic and return some thing useful
      return "This is demo return.Will be replaced";
   }
}

And now you can inherit from this for your other controllers

public class UserController: BaseController 
{
  public ActionResult Index()
  {
    return VieW();
  } 
}     

But In your case, The data you are taking is something specific to your Domain data. so i would suggest you to move it to a different class ( like a new Service / Business Layer)

public static class ProfitAnalysis
{
  public static decimal GetTotalExpense()
  {
     //do your code and return total
  }

}

And you can call it from wherever you wanted like

decimal totalExp=ProfitAnalysis.GetTotalExpense();

And You will soon realize, Having so much ViewData usage is making your code difficult to read and Maintain. Do not wait for that day. Switch to strongly typed classes to pass data.

like image 148
Shyju Avatar answered Mar 02 '26 14:03

Shyju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!