ASP.NET MVC: having one model for all views

纵然是瞬间 提交于 2019-12-06 14:38:11

If you have all these properties on your ViewModel which aren't used (i.e null or whatever) it isn't really going to impact performance. What it will impact however, is your design.

Generally speaking, one model to rule them all as you are proposing is a bit evil and goes against separation of concerns. ViewModel's should be very simple and should be tailored to the view. ViewModel's shouldn't really provide the view with more or less data than what the view needs in order to render.

Consider this....

You have a generic model with 15 properties on it and you only set a handful of them. Somebody else designs a new view and looks at the model, they may not know which of those properties are sent and under what conditions they are set. Consequently they may be attempting to display data that does not exist. This isn't a very clean approach.

I would stick to individual view models and where there is common functionality between views, create an abstraction or base ViewModel from which other view models can extend.

Edit: One other thing you could do is use the new MVC 3 (still in preview) syntax (dynamic) for setting ViewData properties directly as if they were properties.

So rather than doing

ViewData["FirstName"] = "Bob";

You can do

ViewModel.FirstName = "Bob";

This gives you dynamic variables automatically in MVC 3.

There's no reason it shouldn't work.

You can even skip the Model class and create an anonymous type with just the members you need.

return View(new { Amount = 108, Message = "Hello" });

The problem using anonymous types is that you're giving up on auto-completion in the view since you won't be able to type the view according to the model.

Just use dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!