ViewModels, XML and Wizards - asp.net-mvc-3

I am using MVC3, Razor and EF5.
I have now realised that using a ViewModel for each page in a Wizard is a good idea, especially when you need to validate part of a record. I also need to save after each page submit. The Domain model has no validation annotations.
However I have now thought of a better/worse idea???!!! Ultimately I will be generating XML from the DB to put this record into a report. Therefore it could be possible/advisable to have a ViewModel with explicit column names and a domaim Model with just the XML field that all the ViewModel Property data goes into. Thoughts?
Thanks.

Since XML is meant for storage / exchange, I'd think it would just make the ViewModels more complex. I'd think you could write code that turns your ViewModels into XML at the end.

Related

Do we need to use MVC Model DataAnnotation if no validations or Code First Approach are used?

There might be a similar question already or phrased a little bit differently, but I was just wondering if there any valid reasons to use Data Annotations in MVC Models rather then for Model Validations and Code First approach?
The reason I'm asking is that I have a Report page that will never be used for editing, validations and Code First approach
I have created a ReportViewModel where I declared my ReportModels that represent different sections of the report.
I also have a Server Entity that maps the values to the particular Report Model and then the Report Models' properties gets mapped to the view.
Does that make any sense to use DataAnnotations with Report Models at all, if I do not use any editing logic with my report?
Can I just declare properties on my ReportViewModel and map Server Entity data directly to those properties without using Report Models?

Asp.net mvc Data Model or View Model

I am very new to asp.net mvc techniques, and have a question about how to render a view. In my project, I need to retrieve an XML file(XML string) from database. After getting this XML string, I deserialize xml to an object, say LogMessage, which I have defined already. Once I have got such a LogMessage object, I would like to display its contents to the user via a view. Additionally, I need to process some of the LogMessage properties before showing them to the user. For instance, (1) there is a logTime property in the LogMessage object, which is in utc format and I need to convert it to the local time, (2) there is a logCode property, which is in the format of int number (1,2,3, etc), and I need to convert each number to a meaningful name, such as eventStart, eventEnd, etc.
What in my mind now is that I create a strongly-typed view (of LogMessage type) in asp.net mvc3, so that I can render the view with Razor. Also I put all the necessary functions (e.g., for converting utc time to local time, mapping code number to its meaningful name, etc.) in the same view file, and call them when rendering the view.
But I am not sure whether I should do it as the aforementioned way or I should create another view model, say LogMessageViewModel (as I think actually the LogMessage is my data model or not ?). Then once I have got the LogMessage object, I can create a LogMessageViewModel (and LogMesageViewModel looks quite the same as LogMessage), and initialize the LogMessageViewModel with LogMessage and do all the necessary conversions in my Controller or Model, rather than do them in the View. Then now I have all the correct information in the LogMessageViewModel for the view, and create a strongly-typed view of LogMessageViewModel and simply render a view and show its contents to the user.
Could anyone give me some suggestions about these two different approaches or maybe there are some other better ones?
It is always a good practice to keep the DB layer and the UI layer seperate.
When you are getting data from the DB and storing it in a DataContract(LogMessage in your case), Use automappers to map it to a similar viewmodel(LogMessageViewModel ). Then use the viewModel in the views.
the flow goes like this
DB-> XML values -> LogMessage(DataContract/ Domain Object)-> using
AutoMapper -> LogMessageViewModel-> View
A Razor view engine that is used to render a Web Forms page to the response
Please go to here : ASP.NET MVC View Engine Comparison
That link may help your questions
and refer to : Rendering ASP.NET MVC Razor Views
It is always recommened to use ViewModels , if you require any more information that needs to rendered apart from the information from the model
If any additional processing needs to be done, you can do it in your view model.
Then, you can create a view strongly typed with the view model.
Hopw this helps..
If you are not using models, all the transformation logics , additional data needs to sent to view by using view data.
This makes controller fat.
It is a best practice to maintain your controllers as thin as possible.
Since, considering Single responsibilty principle . The responsibity of controllers is only to make transfer of controls.not any other thing else
**Conclusion: *Recommened to use ViewModel in your scenario***
Hope this helps..

Confused: Why to do i have to map my entity object to viewmodel object

i am a complete newbie to the entity framework,mvc just started with it 3 weeks ago.
From then i have been beating around the bush searching for the right approach.the more i dig the more i get lost...i am afraid that i could not proceed any further with using entity framework in mvc
I m lost and frustrated :(
what i have been trying to do is to use entity framework for the MVC application.For that i have started with creating an School.edmx file(which has School.Designer.cs automatically created for it.I dont have any POCO or any others just plain edmx with designer class).Then through some searching i have found that its bad practice to use entity object as model for view.....
Now the real thing started i have made a viewmodel for an entity object.The thing is i dont really get why i have to use a repository and why do i have to map my entity objects and viewmodel objects.Everytime i search why i have to map i get some links saying how to use automapper and the more i search about repository the more i get lost .i dont even understand it.why do i have to map ...??? and why do i have to use repository.
And now the other thing i ask repeatedly to myself is why do i have to write data annotation again in the Viewmodel class when i have already data annotated it in my designer.cs file (like [Required],[Email] and other annotations)..? WHY to write them again!! (If i dont mention them in viewmodel i dont see the annotations working). Duplication of annotation...?
I am lost and i dont even know where i m now
someone give me the right path to follow
Yours Sincerely,
Lost & Confused Newbie
Don't Fret!
Entity Framework is a big beast of a framework based on another beast of a framework: ADO.NET. It's very difficult to truly understand Entity Framework apart from understanding ADO.NET.
That being said, Entity Framework is the perfect tool in some scenarios. However, you (like many of us) seem to have a disconnect about the roles of EF, ASP.NET MVC, and a Repository.
The thing is, you don't need a repository. You don't even need a view model. You don't need EF. And you don't even need ASP.NET MVC. All of these tools are used to make specific jobs easier. None of them have direct ties to each other, and any of them can be used independently of each other.
A Repository: is used to put certain objects into some persistent place, so that you can get them later. That's really all it is.
ASP.NET MVC: Is an HTTP Handler that takes the requested URL and instantiates a controller class which in turn serves up views. The views display some model, and because the views are interactive, they allow the user to send yet another request, starting the whole thing over again. Because this process is (intentionally, but not necessarily) stateless, some sort of persistence is required. This persistence can be a file on the server, a file database, or in most cases a relational database.
Entity Framework: sits on top of ADO.NET (Microsoft's relational database abstraction framework), and allows you to map objects from a graphical (in memory) form to a relational (in-database) form, and back again. The idea is to allow the developer to easily map objects to and from the database. However, this is not a simple process, and because you're not directly interacting with the database (be it via ADO.NET or not), there is some inherent complexity. One of those complexities is the display of the information.
View Models (asp.net mvc view models): allow models to be displayed in various forms. For instance, we may have a "scholastic record" table, and a "person" table, and together they might form a "student". Because our entities are "ScholasticRecord" and "Person", we cannot (as) simply display the information on the view. For this reason, we create a view model to combine and display the information as a "Student".
View Models also prevents us from accidentally calling "lazy" methods on our entities while in the view, which might query the database. This isn't bad, but it could get confusing, because our view is doing repository-like work (which isn't very [S]OLID).
TLDR;
The reason you're having trouble is probably because you're trying to do everything at once. I would suggest using the tools you know, in addition to maybe one or two that you do not. Try using Entity Framework and ASP.NET MVC together, but don't worry about the Repository pattern just yet. It can be difficult to use EF with a Repository, unless you have a lot of experience with either or both.
ASP.NET MVC Tutorials with Entity Framework:
http://www.asp.net/mvc/tutorials/mvc-music-store
(notice how they use models directly in the view, sometimes)
The thing is i dont really get why i have to use a repository
MVC helps you write code that has a clear separation of concerns. In this case, the repository is meant to how the application interacts with the data storage for a specific entity. If you want a Student entity you call StudentRepository.GetEntity(). If you want to save to save you call the StudentRepository.SaveEntity(Student student).
Why do i have to map my entity objects and viewmodel objects.Everytime i search why i have to map i get some links saying how to use automapper and the more i search about repository the more i get lost.
While you can use these entities directly in your view for simple cases, the problem comes up when you have more complex views - composite views that may need multiple entities, views that need to expose only a subset of an entity or even a subset of multiple entities. So yes, you can just expose your entity directly but I find it easier just to create a separate view model.
Automapper is used to help map from view model to entity. So, instead of writing a lot of
entity.Name = viewModel.Name;
entity.Age = viewModel.Age;
...
Automapper is used to automatically map these properties.
And now the other thing i ask repeatedly to myself is why do i have to write data annotation again in the Viewmodel class when i have already data annotated it in my designer.cs file (like [Required],[Email] and other annotations)..?
You should specify validation logic specific for each view in the view model so that if validation fails at the controller it can stop processing instead of continuing. Even though mapping your view model to an entity and trying to save would be prevented by the entities data annotation, I find it clearer to look at a view and its view model to understand what's going on instead of going from view to view model to entity.
Update:
Take a look at ASP.NET MVC View Model Patterns and How we do MVC – View models. I found them both useful when trying to understand view models.

Applying MVVM to ASP.NET MVC. How to do property mapping?

There are a lot of articles about using MVVM patterm for ASP .NET MVC. For example, it is http://blogs.microsoft.co.il/blogs/helpercoil/archive/2010/08/28/asp-net-mvc-and-the-mvvm-pattern.aspx.
There is only one question for me. We have a lot of ViewModels for one Model. How can I fill Model properties automatic by using viewModel object? How to make automatic property mapping?
I use Entity Framework.
For example, I have model Test with the following properties:
id
name
title
idUser
idCompany
I made ViewModel for my task. This ViewModel (TestUserViewModel) uses for simple user with the following properies:
- id
- name
- title
For example, user edit an existing test. As the result, we have an object with type TestUserViewModel. I want:
synchronize Model object and ViewModel.
save the default valies for idCompany, idUser - for properties, which were excluded from current ViewModel.
use some automatic stuff - it may be something like ApplyCurrentValues. I really don't want to write a lot of following code:
modelObj.name=viewModelObj.name;
modelObj.title=viewModelObj.title;
Using System.Reflexion for this looks like bad, too.
So, how to do it?
If you don't want to write a lot of mapping code from one object to another you might want to look into mapping tools like AutoMapper http://automapper.org/
Having said that, as #Darin Dimitrov pointed out, you should review your architecture too. If you are doing ASP.NET MVC you should become more familiar with MVC rather than MVVM. As you read more about how to use MVC you are going to start seeing the use of "viewModels". Keep in mind that these "viewModels" in MVC have nothing to do with "VM" in "MVVM".

Need expert's voice for mvc beginner about Controller & Model

I am quite new to MVC. I am having the following questions, please help me clarify those questions, thanks a lot.
Q1. Where should I populate my view model? e.g. My view model is very big, and contains a lot of the dropdown listbox, multi select list and the other few complex objects. I am currently populate them inside the view model self, by passing the model through the constructor, and load all the object data within the constructor. I also see my college populate the viewmodel inside controller. so I am confusing now, coz lots of people suggest to keep the controller small and skinny.
Q2. We are using the linq2sql as data access layer, should I use the table entity in my viewmodel instead of creating separate model class? Expert said it's bad, but if create seperate model class, I basically repeat them and I also need to copy those value to linq 2sql entity every time when I want to persist data, it's not that fun, too much work.
lots of people suggest to keep the controller small and skinny.
Yes. What people mean is that the controller should not contain any logic, except for model <-> view mapping. With model I mean the "M" in MVC.
Q2. We are using the linq2sql as data access layer, should I use the table entity in my viewmodel instead of creating separate model class? Expert said it's bad, but if create seperate model class, I basically repeat them and I also need to copy those value to linq 2sql entity every time when I want to persist data, it's not that fun, too much work.
No. You should not. Read my answer here: ASP.NET MVC Where to put custom validation attributes
Use a mapping framework for the model -> viewmodel conversion.
Update:
From what I understand, you suggest to assembly the viewmodel inside the controller (I mean call the business layer or repository to get my data) and use controller to call the business logic dealing with the data, am I right?
yes. The controller is really a glue between your business layer / repositories and your views. The views (and view models) should know nothing about them and the business layer / repositories should know nothing about the controller/view.
The controller was created for just that purpose. To create an abstraction between the user interface layer and the lower layers. Hence the only code that should exist in the controller is to make that possible (and therefore following the Single Responsibility Principle)
If you start adding that logic into your view models you start to add coupling between the lower layers and the user interface layer. Doing any changes in the lower layers will therefore also affect all your view models (instead of just the controller
your viewmodel should be a poco, and should most certainly not be handling the mapping of the model. if you don't want to map your model to your viewmodel in the controller i would suggest you look at something like automapper. it makes it easy.
once you've mapped from your model to your viewmodel, any extra properties that need to be set such as your lists should be set in the controller.
as i stated previously, definitely don't tie your viewmodel to your current orm or table structure. you never know what might need to be refactored, and if you can handle it via an automapper mapping instead of changing your view and viewmodel then you've saved yourself a significant amount of time.

Resources