Tuples vs ViewModel in MVC - c#

Hi I am new to MVC and I have to create a dashboard page in my applications which has 4 different zones having data related to different models. And i have to make my view strongly typed view. Though I accomplished the task using Tuple in my view.
#model Tuple<ModelFirst, ModelSecond, ModelThird, ModelFourth>
The question is which is a better way using Tuple or creating a ViewModel having only the desired properties. I have to keep in mind both the performance and number of Lines of codes.

Usually view models have metadata associated with them which among other allows you to perform validation and integrates with editor/display templates. Tuples don't seem appropriate. Another disadvantage is that they express less clearly the purpose of each property in the view model (Model.Item1.x, Model.Item2.x, ..., no-one else than the original developer can make any sense of this, and if he is like me after few days even he won't be able to make sense).
quotation from #Darin Dimitrov

Related

asp.net mvc - nearly identical ViewModels [duplicate]

This question already has answers here:
Why do we use ViewModels?
(4 answers)
Closed 5 years ago.
I am building a web application with ASP.NET MVC and am still a beginner with this technology.
I have learned that it is best practice to have a ViewModel for each View. I can understand why this is a good idea. However, in my situation it seems to create a lot of extra work.
I have a model called Rule.
It contains an Id, Title, Description, LastModifiedDate, CreatedDate, among other fields.
I have an Edit, Create and Details view for the Rule model.
According to the best practice, I have to make a ViewModel for each of the above Views. But the ViewModels for above Views are nearly identical. One of the only differences is that the Create-ViewModel has no Id, but the Details and Edit ViewModels do. Other than that, the ViewModels are nearly identical. That is, they contain the same attributes and same DataAnnotation validation fields.
Why do I think this is troublesome? Suppose I want to change some of the Data Annotations. E.g. chaneg a Maximum Length of a string attribute. If I wish to do so, I have to do so in both the Rule model, the Create ViewModel and Edit ViewModel. And likewise if I wish to add new attributes, I must do so in all the models.
Am I doing this right, or can it be simplified?
Well this is more an implementation decision rather than a best practice rule. You have to take in consideration some of the pros and cons:
Different ViewModel for each view
Modify only the ViewModel associated with the view
Flexibility
Hard to maintain with very large applications
Reuse ViewModels for different views
Modify all the ViewModels at once
Much easier to maintain
Limited flexibility
My advice would be to create the base RuleViewModel without the ID property and for the edit and details actions inherit the model and add the additional column.
It is/was never a rule to make ViewModel per View. It is all about how your architecture is. As per your requirement if you feel both the views are exact same then use same ViewModel.
IMO do not use data annotation, if possible go for Fluent Api.
For all operations: add, update, remove - you can use one view model - Rule. It is completely fine as you want to manipulate with this single object, right?
The only difference would be the displaying of multiple Rule objects - list view page, here you might want to create an extra viewmodel like RuleListViewModel which will contain a collection (IEnumerable<Rule>) of objects and maybe some more properties for filtering and so on.
It sounds like you are mixing your view models and business objects. I usually try to keep these separate as they serve different purposes.
Your business object can have CRUD methods. Your view model can have a property that exposes your object, and can in fact expose other objects if required.
Doing it this way preserves the single use rule and makes it very maintainable.
But, this really is a design choice rather than "best practice" which (let's be honest) changes with the wind.

Should there be only one ViewModel class in MVVM pattern?

I am trying to understand the MVVM pattern and there is some issue that is not clear. My Xamarin Forms application will have several Views (which is quite obvious). Must everyone of them be binded to different ModelView class? Or maybe there should be only one MV?
Yes and No
Yes -> Basically the idea is that your ViewModel should only be used by one view. If you use a ViewModel to populate an area or whatever then that ViewModel is "reused" each time that view is presented in difference places.
No -> You can use multiple models in a view model. The purpose of the view model is to abstract away the business / data layer (i.e. the model).
However, using more than one model usually indicates that the view is too large. You might want to split it into user controls (which have their own view models).
References:
With MVVM, does each UI window have its own ViewModel?
In MVVM, is every ViewModel coupled to just one Model?
I've always thought of "each View has its own VM" - the model as being a sub-set of a comprehensive design.
I will say from painful experience: do not design models in isolation based solely on the view/UI they support. Without a comprehensive model back end you will have a hard time integrating all of the pieces into a coherent, complete business model that works. Anemic classes, redundant bits, incomplete and wrong validations, same properties-different names, incompatibilities w/ existing code, gobs of hacky glue code, Programmers breaking each other's code, no re-usability, no reuse of existing classes. For us it all came to a head in a 3 month test-fail-fix tilt-a-whirl of embarrassment.

Polymorphic MVC Views

So I am making a registration page in ASP.NET MVC and theres a list of fields which changes depending on a number of conditions (taken from a database).
What would be considered the best approach for displaying these fields on a view without code changes each time the DB is updated.
The current system I am thinking about is making a Dictionary with "Name, DataType" then just iterating through the list and putting a new input type of each name (using a switch for data type to get the correct editor). But it seems like a old fashioned and not fully utilizing the benefits of the .NET MVC system (such as validation, default values, customized editors for specific content).
Is there a approach I may possibly be not aware of in .NET to handle this problem?
I had very similar problem. Posting is here.
No, there is no polymorphism views in ASP.NET MVC. At least I couldn't make it work doing tons and tons of experimentation and asking this question several times in different ways on Stack Overflow.
The type of #model defined in the view will define its type inside the view, rather than actual type of the model (in case it was interface or abstract class or base class, while you passing in child class with all your beautiful decorations, which won't work, since type is defined by model type).
Sorry, no positive answer to your question. I ended up writing bunch of editor templates, which were only different by model type inside. Huge DRY violation, but this is the way ASP MVC worked, unfortunately.
Hope this helps saving you some time.

MVC pattern implementation. What is the n-relation between its components

I'm working in a C# project and we are , in order to get some unity across the different parts of our UI, trying to use the MVC pattern. The client is windows form based and I'm trying to create a simple MVC pattern implementation.
It's been more challenging than expected, but I still have some questions regarding the MVC pattern. The problem comes mostly from the n-n relationships between its components: Here is what I've understood, but I'm not sure at all of it. Maybe someone can correct me?
Model: can be shared among different Views. 1-n relationship between Model-View
View: shows the state of the model. only one controller (can be shared among different views?). 1-1 relationship with the Model, 1-1 relationship with the controller
Controller: handles the user actions on the view and updates the model. One controller can be shared among different views, a controller interacts only with one model?
I'm not sure about the two last ones:
Can a view have several controller? Or can a view share a controller with another view? Or is it only a 1:1 relationship?
Can a controller handle several views? can it interact with several models?
Also, I take advantage of this question to ask another MVC related question. I've suppressed all the synchronous calls between the different members of the MVC, making use of the events and delegates. One last call is still synchronous and is actually the most important one: The call between the view and the controller is still synchronous, as I need to know rather the controller has been able to handle the user's action or not. This is very bad as it means that I could block the UI thread (hence the client itself) while the controller is processing or doing some work. How can I avoid this? I can make use of the callback but then how do i know to which event the callback comes from?
PS: I can't change the pattern at this stage, so please avoid answers of type "use MVP or MVVC, etc ;)
Thanks!
Model, View, and Controller are conceptual layers, not individual objects, so honestly it doesn't make a whole lot of sense to be thinking of them in terms of multiplicities. Nevertheless, I can try to approximate an answer for you.
A Controller returns a single result for a single action; that result may be an actual view or it may be something else. However, the Controller doesn't really actually have any interaction with the view; all it does is provide one or two pieces of information in its result: The name of the view that should be used and (optionally) the model used to populate. It's up to the View Engine to actually create and bind the view, which is a considerable departure from normal Smart Client UI logic.
A Controller may interact with several different pieces of the Model, or not interact with it at all in some cases; there is no rule for that side of the relationship. In an action result, a Controller has to give back either 0 or 1 instances of a "model", but this may not be the true Domain Model, it could be a View Model.
A View is generally bound to exactly one Model (or View Model), although in some cases a View might simply be content and therefore not bound to anything.
So, in the very crude UMLesque parlance:
Controller:Model = 0..* : 0..*
Controller:View = 0..* : 0..1 (request) or 0..* : 0..* (overall)
View:Model = 0..* : 0..1
This is all specific to ASP.NET MVC. If you were designing your own MVC implementation then obviously you could choose to implement it any way you like. Good luck implementing MVC in WinForms, though; Forms don't behave like Views at all, even patterns like MVP/MVVM are quite difficult (though not impossible, c.f. Microsoft's CAB/SCSF) until you move to WPF.
I´ve implemented the MVC pattern in C#. Don´t know very much about theory, or how it should be, or shouldn´t be. I just think that the pattern is the base idea, and then, you can use this idea in many different ways, depending on your own needs. I´ll tell you about my implementation, and hope it helps you.
**The Model**
Your description is pretty clear, so don´t have much more to said. Here is where I define my bussiness objects. I take advantage of this layer to include objects validation rules.
**The Controller**
In addition to handle the user actions and update the view, I have a Unit Of Work for each controller. I check that the objects in the view pass the validations (defined in the model layer) before commit changes in the Unit Of Work.
In my case, one controller can manage many models, and I like to have only one view in each controller.
Like a suggestion, I´d like to use my Framework with diferent UI, so I have an abstract implementation of Controller, and then I have specific controller implementations for different interfaces (WebForms, WinForms, ...).
**The Views**
In your case, we could call them, simply, the forms, the UI, ... I like to organize my desktop applications as if they were web applications, using tabs. One tab represents one controller, and so on, one view, and one or more models.
In conclussion, and in my case:
n models - 1 controller
1 controller - 1 view
--
n models - 1 view
You're probably over-thinking and over-formalizing it a bit.
Here's how I look at it:
Model: This is the actual thing that does real work.
Controller: This is the thing that sends inputs into the model, so it will do work.
View: This displays the results.
That's it. The easiest analogy to use is a console application - the app is the model, STDIN is the controller, and STDOUT is the view.
Extending that analogy, many GUI apps are built on top of command-line apps by attaching to STDIN/STDOUT. In that case, the things sending data to STDIN are the controller, the things taking data from STDOUT and putting on the window are the View, and the console app is still the model.
It's CS 101 again - input, processing, output. It's only trickier for a GUI app because the input and output are typically on the same window.
You (obviously) don't need to actually have a console app to do this - the separations can be done even in a single process. All the other weird wiring stuff that takes place is just whatever is needed to get this relationship between the parts to work. But the wiring isn't the important bit - the important bit is the separation of responsibilities and logical organization of the code.
So, whether 1 view must map to 1 controller, or any other orthognality issues are secondary. In fact, you should probably just do whatever your problem domain requires, but I'd (as typical) argue against over-eager generalization of code - IOW, don't mush things together that aren't really the same.

Merits/demerits of using duck typed view models with ASP.NET MVC?

What are the benefits/demerits of using duck typed view models with asp.net mvc?
Recently I've seen an interesting implementation of a twitter search client, using fluent C# dynamic XML wrapper to pass data from the controller to the view, to wrap XML data.
It seems like a better way to pass data - viewModel.Foo instead of using ViewData["Foo"] or Foo.Bar instead of XElement("Foo").Attribute("Bar").Value in terms of cleaner code - but I assume it will be having performance issues.
Benefits - less code (literally) and readability (in cotrast to ViewData["foo"] approach).
Drawbacks - you lose strongly typed view model (and that's something i can't live with). Higher dependency on unit tests. And I'm not sure how things like Mvc2 templates/validation can be attached to dynamic view model.
In case you are not familiar with view model idea - take a look at this. It's way much more powerful beast than it seems at first.

Categories