Sharing a complex ViewModel with multiple simple Views - asp.net-mvc

I have a single View being sent a ViewModel with 20 properties. Now there is a requirement to split the single page into 10 pages, each with 2 properties. My initial gut feeling was to cut the ViewModel up into 10 smaller VMs with 2 properties each, but then I thought, does it matter if 10 different Views all share the same ViewModel and just use the properties they need? I feel like that's the wrong approach but I can't really think of why...

Go with your gut and break it into 10 pieces. Leaving it as-is is certainly the easy way out, but will cause headaches down the road as the site grows/morphs. The MVC gods didn't intend for us to have a huge ViewModel lurking around that pages pick pieces off as needed. Stay tightly-coupled.

Related

Map one entity to one viewmodel or to many viewmodels

I have for one customer entity multiple viewmodels depending on the existing views like Create,Update,Get,Delete. These viewmodels share the same properties up to 75% with the entity.
Should I better merge all the customer viewmodels to one big viewmodel?
So I have to map only and always from one entity to one viewmodel and the way back?
Do you see any disadvantage in flexibility for certain scenarios I have not in my mind now?
In the long run, keeping them separate will be better because while the data contained in each ViewModel may be similar or even identical, the intention is different. For example, the Create and Update ViewModels are certainly similar, but have a few important differences. First, the Create view model usually doesn't have the identity of the entity and having it there may be confusing since it doesn't make sense. Second, if the application supports partial updates, the update ViewModel may be a collection of changes to an existing entity, not the entity as a whole.
If you are striving for DRY you can achieve re-usability by means other than sharing the entire ViewModel class. Instead, you can create smaller re-usable components and re-use by composition instead of inheritance. Attempting to coerce a single ViewModel class to fulfill all requirements will be buggy beacause the code is more difficult to reason about. Many times, simple copy & paste gets the job done better than what OOP offers.
On one hand, splitting up the ViewModels as you describe makes your code base really clear, as you can make sure each ViewModel is exactly fit for purpose and has no unnecessary properties. On the other hand, it means that you have more code to maintain - a change to your entity may well mean changes to several ViewModels.
On the other hand, the one big ViewModel approach has basically exactly the opposite pros and cons - less code to maintain, but the ViewModels are less fit for purpose.
There isn't really a right or wrong answer here, you've got too weigh up the pros and cons of each approach and decide what will work best for you.
One sort of halfway approach is to have a single ViewModel for Create/Update, one for Retrieve and one for Delete, as the Create/Update are likely to be very similar.
Another, most OO option for you lies in good old inheritance: define common functionality between actions in one class MyVM and extend it (inherit from it) as you see fit for different actions: MyVMEdit, MyVMDelete, MyVMCreate, `MyVMList'.
This is the best of both worlds: you only maintain things once, and you extend them to fit precisely to every view.
There is no right approach here, since its not a math, any approach you take that gets job done will get the job done :) But ... sometimes we carried away from our roots too far :) its pure good old Object Oriented approach.
If inheritance (or extension) poses any issues (for any reason), you can embed MyVM portion inside every MyVM<Action> model and achieve the same level of abstraction / functionality balance.
As usual - right tool for the right job.
Hope this will help you.

Partial controls in Asp.net mvc page

At my new job, I was given some MVC work. There is only one controller with nine action methods(6 are for ajax rendering) . The page was bit large, so I divided it into small your controls and used render partial to render them. Some user controls were being render through ajax also. Most of the controls are not more like foreach loops and rendering some data from tables, not more 10-15 lines. The main index page passes model to all the controls. My main page looked very clean and easy to maintain.
But my team members are saying, I should put everything in the main page rather than building small controls. Their point is number of files will be a lot, if we start creating controls like this. Also they say if we are not reusing these controls somewhere else there is no point creating them separately.
I would like to know what is better approach for this kind of scenario. Any good links which can help us to understand things better, or any book we can read to clarify our questions.
Help will be appreciated.
Regards
Parminder
As a preface to my answer, let me mention the important value of maintainability. Software evolves over time... and must change to fit the need of the application.
Maintainability in code does not magically appear... Sacrifices (with a touch of paranoia sometimes) must be made in your coding style now, to have the flexibility you'd like in the future.
There may a large page in your project. Some may say that if it works, no need to fix it. But that's looking at it from a short term perspective. You may need some of those UI interfaces in other places in the future. What some persons may do (rather than make partials) is copy that code in the places where they need it - thus causing the same bloat over time that they were trying to avoid.
If you're on the project in the long haul, you'll more fully appreciate the need for flexibility over time. You can see that there are patterns that you'll want to re-use.
My suggestion then: Partials and controls are good things... they are good investments for your ease in the future. If you forecast reusability, that's a good sign for using them.
But use them sparingly. Don't micromanage everything on a page. Some things may be itching to be 'component-ized' but sometimes it's best to SSFL (Save some for later). Like everything in life, balance is important.
Having clean concise code is the way to go. Your code will be alot more readable if you utilize :
sections
templates
partial views
Just remember its always easier to navigate folder structure than to read 100's - 1000's of lines of code.
I recommend watching "Putting your controllers on a diet" by Jimmy Bogard.
Also read "Fat Controllers" by Ian Cooper.
these two links will give you a good idea on how to structure your MVC apps.

how big should your controllers be in asp.net-mvc

i see the new feature of areas in asp.net-mvc 2. it got me thinking. why would i need this? i did some reading on the use cases and it came down to a specific point to me around how big and how broad scope should my controllers should be?
should i try to have many little controllers? one big controller?
how do people determine the sweet spot for number of controllers? i think mine are maybe too large (which had me questioning areas in the first place as maybe my controller name should really be an area and have a number of smaller controllers)
I like to think of controllers in terms of domain areas they are responsible for. As such, you can always merge and split them to find the balance.
For example, you can have one giant controller for the domain User. Or you could split it into areas like User/Settings, User/Profile, User/Orders, User/Statistics etc. When they grow you divide them further like User/OrderingStatistics, User/VisitStatistics, User/ItemGroupStatistics etc.

Using partial views to simplify a complex view - a good approach?

Is it correct to use partial views for the SOLE purpose of breaking down a more complicated view into separate chunks and therefore making it more readable?
It probably seems a silly question but the reason I ask is that everything I've read about using partial views involves a piece of the UI being re-used in multiple places. In my case the piece of UI being put into the partial view is only used in one place. It is therefore done solely for readability, but I'm not sure if the performance impact of this may outweight the increased readability. Thoughts?
Whilst this is correct there are more uses.
Reusability
Ability to pass pack rendered html
from your controller so you can
append the partial view to the bottom
of containers. Great for jQuery
async calls
Seperation of concerns
Gives developers the ability to work
on different sections of a page w/out
getting in each others way.
Just to name a few.
I think that you shouldn't be worried about performance until it is a real problem, but you should be worried about your code from the first moment. I usually use partial views to simplify the logic or the structure of my views, as you are wanting to do.
Sure, that's an okay use for them. If it keeps the page organized so it's easier to maintain, I think it's fine.
Also, if I'm using caching, I find it easier to have my:
cache "this" do
# render partial
end
I find it easier to read and keep track of things, especially on an overview or dashboard page where there are lots of different parts of the pages that you're including.
I tend to be a bit more conservative. I only use a partial view when I know I'll need to reuse the code or I have multiple complex objects in ViewData that need to be displayed.
There's no right or wrong way here but I have worked on projects where there are a ton of partial views to make things "more simple" and I end up spending forever trying to track down where all the partials are (controller/action folder, shared folder, or elsewhere).
One thing about my approach though is if you have even the slightest thought that the view code may be reused down the line as the project changes use a partial. It will save a bunch of time down the road.
I veto any large and complex view in our projects. Instead, we use RenderAction to extract those pieces of code into smaller chunks/parts. I blogged about it here:
http://eduncan911.com/blog/html-renderaction-for-asp-net-mvc-1-0.aspx
Basically, you move that logic and/or parts into Controllers.
Or, if you are just talking html - then yes, breaking down a view into RenderPartials works too.

Which multi-language web architecture works best (multiple views/single view)?

I want to support just 2 languages. There will be no requirement for any additional language. What will be the best approach after considering both ease of use and maintenability:
(a) Each view has a separate page for each language and they will share controllers and model dlls
(b) Both languages pump resources into the same view template
Please don't bother about the url structure right now. I will appreciate real experiences over the theoretical discourses of pros and cons. Thanks for your help.
Mutliple views are more flexiable clearly and if you only have 2 then that is a possibility but its still a pain.
However having just 2 instead of N to worry about means you can probably take both into consideration when creating the views in the first place. Hence instead creating multiple views create a single view that uses resources and works in both languages.
Depends on how different you expect the localized versions to get. If you are pretty confident they will always be almost identical, simply different words in each placeholder, then a single view model would probably be the way to go.
However, what I have found to work when there is a blend between the two (i.e. some views are the same, just translated; others end up being somewhat different) is to build a provider model into each view and sub-view, so when the view engine goes to load a view, there is isolated logic in the provider factory to determine, for that particular view, whether to use the same for both languages or switch.

Resources