0

I have a controller that runs some calculation on data, and then I need to return the calculation to a view. I understand that I can accomplish this through the ViewBag, but I would like to know the best practice for doing this. Are these LINQ queries something that should just be executed in the View?

public ViewResult Results()
{
    var surveyresponsemodels = db.SurveyResponseModels.Include(
        s => s.SurveyProgramModel).Include(s => s.PersonModel);

    ViewBag.PatientFollowUpResult = db.SurveyResponseModels.Count(
        r => r.PatientFollowUp);

    ViewBag.ChangeCodingPractice = db.SurveyResponseModels.Count(
        r => r.ChangeCodingPractice);

    ViewBag.CountTotal = db.SurveyResponseModels.Count();

    return View(surveyresponsemodels.ToList());
 }
gdoron
  • 147,333
  • 58
  • 291
  • 367
user547794
  • 14,263
  • 36
  • 103
  • 152
  • If I were you, I would create a viewmodel that the view would consume. I would not do the calculation in the view. Yeah, what gdoron said... – C Newey Jun 21 '12 at 17:58

1 Answers1

4

The best practice is not using ViewBag at all.

Put all the data you want you want to use in the View in your ViewModel.

Keep the View clean for calculations, and use it only for presentations.

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • I guess the part where I'm confused is that I want to display the data only from a single model (rather than combining multiple models), but I just want to perform some calculations on that model and send the calculations back to the view. Create a viewmodel with these calculations, won't I essentially be storing the calculations in a database and retrieving with a viewModel? – user547794 Jun 21 '12 at 18:28
  • @user547794. You can create a big model with small models inside of it. That is the best way. Though you can write LINQ and a lot of C# code inside the View, it's deprecated. – gdoron Jun 21 '12 at 18:52