Fabio
Fabio

Reputation: 1066

ASPNET MVC - What goes into the model?

I have noticed a pattern that in some MVC applications I inherited from a previous developer. When defining the models all the information containing the items for selects and check-boxes are passed in the model.

public class MyModel
{
   int MyEntityField1 {get;set;}
   string MyEntityField2 {get;set;}
   public selectList SelectItens1 {get;set;}
   public selectList SelectItens2 {get;set;}
}
...
MyModelInstance.SelectItens1  = new selectlist(...
MyModelInstance.SelectItens2  = new selectlist(...
return view (MyModelInstance);

the information on SelectItens1 and SelectItens2 is one way. What is the advantage of doing as above instead of using the ViewBag to pass Select Items to the view ?

public class MyModel
{
   int MyEntityField1 {get;set;}
   string MyEntityField2 {get;set;}
}
...
Viewbag.SelectItems1 = new SelectList ( ...
Viewbag.SelectItems2 = new SelectList ( ...
return view (MyModelInstance);

I think it just makes the model fat for no gain whatsoever.

Please advise.

Upvotes: 0

Views: 166

Answers (2)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Both approaches are fine, its just a developer preference

First Approach: There is no harm in having the SelectListItem within your model, Moreover it gives you a clear picture of what the fields must be in your UI, So looking at the model you can confirm that the UI needs to render a dropdown list control for the 2 properties in your example.

Second Approach: If this model is used only in one or minimal pages then Viewbag should be okay. Again this might mean that the developer must have knowledge on what control the UI must render.

So the approaches are purely developers choice and I don't see any major performance improvements of one over the other.

I personally use the first approach as it more clean and keeps the controller code less.

Upvotes: 1

JammerUK
JammerUK

Reputation: 106

Generally I would agree that models should be kept to the minimum.

However with Microsoft ASPNET MVC pattern you want to keep your controller clean and Microsoft they recommended approach is to fatten your Model and not your controller!

"In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder."

https://www.asp.net/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

Upvotes: 0

Related Questions