How should we pass a data to a view in a big ASP.NET MVC web site

霸气de小男生 提交于 2020-01-24 17:12:44

问题


First of all, I have been a php programmer for a long time and I am a mvc programmer newly. I did a few minor web sites that each have one or two controller at most. But I've started a website that will be very major web site. There will be a lot of data to pass to views. Now, normally I try to use model approach every time instead of ViewBag or ViewData approach. If the view demands more data, then I change the model class and then recompile the project. Especially, if the topic is an index page, the data to pass to the index's view changes every time. In a big web site, I'll use a lot of partial view that uses different models. So every time, I will have to change the index's model to support those partial views in the index view. if I add a new partial view into index view, I have to add the partial's model into the index's model. I implement an IndexModel class for an index view every time when I start a website. Then I add properties to this model every time when I add a new partial view to the index. Now is this a correct approach or should I use ViewBag or ViewData for partials' models. I think the real question is when we should use the model approach and when we shouldn't... If you share your experiences, I would be grateful.

回答1:


The MVC approach you should use always, especially for simple sites, it's save your time and make application more understandable.

If you write something larger than two pages, you need to use MVVM pattern (growth of MVC), in that case you will escape from using "partial models" with ViewModels.

Model must contain only busines logic.

Be better if you will always use ViewModel (not a Model) for returning data from a view and pass it to view, because it provides some safety.

For facilitate the procedure of copy data from Models to ViewModels use the things like AutoMaper and EmitMapper.

ViewBag and ViewData you should use only for additional data's like item colections for DropDown, or some view-text like page title.

One more advantage of MVVM pattern is better testability. If you write and support really hugh site you may write tests for some responsible parts of code.

For more details you can look at google - MVVM, ASP-MVC.

If i something not understad in you question or miss, write it in the comment ("add comment" ref).




回答2:


I personally prefer to keep my sites consistant and always use Model + Viewmodel (no matter how big the site is) despite the extra work (which isn't much anyway).

It helps with maintainability. I know where and how everything is stored and coded into the site.



来源:https://stackoverflow.com/questions/7539069/how-should-we-pass-a-data-to-a-view-in-a-big-asp-net-mvc-web-site

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