Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number/Date Conversion helpers in MVC, where to use them?

Tags:

asp.net-mvc

Stackoverflow is built on MVC and does a bunch of simple but nice things with dates and numbers (answer counts, votes, etc...). I'm assuming this is all done with a couple of static helper classes.

My question is should the view call these helper objects or should the controller call these helper objects and embed the result into the ViewData?

  1. Controller Populates View Data

    • Controller Loads Model/Data
    • Controller uses DateHelper static method to convert date to friendly string
    • Friendly date string is provided to view via ViewData
  2. Controller Populates View Data with Model and View calls DateHelper

    • Controller Loads Model/Data
    • Controller provides model to view via ViewData
    • When ViewData is binding to HTML it calls DateHelper static method

I suspect number 1 is the right way to go, but it seems a bit messy in that you can take a List of models and those are easy to loop over in the View. If you process and generate a bunch of friendly strings based on a set of model instances and the model doesn't have a place for those to be attached to a specific instance you end up sending two different lists of data to ViewData. Right?

Your thoughts are appreciated.

like image 928
Eric Schoonover Avatar asked Nov 19 '25 23:11

Eric Schoonover


2 Answers

Depending on who you ask, you'll get different answers. I personally like option #2 as I want the ViewData to be raw data and choose how it is rendered in the View. To me, that's perfectly fine to do that in the view as it's a view concern.

However, I know people on my own team that disagree with me, suggesting that the controller is returning a presentation model, not just a model (I do agree with that as well) and it should handle all these conversions before sending the model to the view. The view in this case should be super dumb.

I don't think there's one absolute right choice for everybody in this case. I'd say pick one or the other based on your experience and stick to it.

like image 173
Haacked Avatar answered Nov 21 '25 21:11

Haacked


I think I would prefer to use the helper in the view. In my opinion, how a date gets rendered is a view centric thing. The controller just knows that the view needs to display it.

like image 25
Rob Avatar answered Nov 21 '25 21:11

Rob



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!