Inject data annotation attributes to ViewModel - data-annotations

I am looking for solution to inject data annotation attributes to ViewModels in MVC. The idea is decorate the ViewModel class with Related Entity and the edmx file path and then read the Edmx file and the entity metat data information. Once entity meta data identified iterate through the properties of the view model, locate the matching entity attribute then decorate the view model with RequiredAttribute, StringLengthAttribute etc based on entity information.
Is it possible to use the t4 templates, since I have to read teh existing .cs file created by the user, modify and Save it.
How can i achieve this? Pls advice.

Related

How to fetch xml file data to grid in mvc application

I need to create a mvc application which contain on grid view, that contains the data of the xml file, so I need to read xml file data and display that data in grid using mvc
We cannot write code for that. But I can suggest you that use XMLSerialization and map all XML data to Property Class and pass object of that property class to view as a model.
And in your view you can simply use all properties of that model.
References:
How to serialize and deserialize XML
List Model Binding in MVC

Creating and Editing related entities from a ASP.NET MVC web form

I'm creating a ASP.NET MVC 4 web app with a database and Entity Framework 5 for a web form to maintain Document (aka Contract) entries.
Below is a sample ERD (in the form of edmx diagram with navigational properties) I have created for a DB in SQL server. For MVC web app the Model is generated from the DB with .edmx file.
Based on the Model, I have setup a form which can create and edit a Document like so:
Document Create and Edit View
This view refers to Document model class. So all the input fields using html helper (Html.TextBoxFor...,etc) are referred from Document object and its related objects (Section 1 & Section 2). The checkbox hides and shows the subform for a section with JS/jQuery. For the Edit view I use same as Create view, except it contains additional hidden ID fields to identity the records to edit from the DB.
I have added a variable length list for section item addition by following this:
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
In the partial view for the items dynamic list I use Section1Item and Section2Item as model reference.
Document Controller's Create method
So on Create the document object posted in Create(...) method contains all the attributes from the Document including the section's attributes.
If the checkbox value for Section 1 & Section 2 are false then I set the Document's Section 1 & Section 2 to null like so:
if (section1_chkbox == false) {
document.Section1 = null;
}
I have to add each item from the dynamic list into the document object like so:
foreach(Section1Item item in itemsList) {
document.Section1.Section1Items.Add(item);
}
So finally the Create method in the DocumentController adds the document in a db context and saves changes. The document and its related entities are successfully added to database tables.
Document Controller's Edit method
But when I'm editing the document with the Edit method in DocumentController there are some inconsistencies with some section1 object's ID being null for some related objects in Section1Items. For example when Section1Items are present the posted Document object (for edit) does not contain reference to Section 1 object's ID.
So it is fiddly and messy to update an existing document record as I'm having to check the ID attributes of a object. There are always errors like inconsistent principal and dependent objects in the relationship when saving or setting the object's entry state to modified.
My Question
How can I setup the View and Controller to achieve a functioning Create and Edit of a document along with its related entities as in the form's interface able? I need a efficient and correct way to use Entity Framework for this. How can I use view models for this if that would make this easier?
From what you described here I understand that there is a problem with virtual reference to Section1 from Section1Items. So in other words the problem is that entity framework model doesn't suit you display needs. You would need to render duplicated entities to map entier Document in your view. Am I right?
If that's the case I see two solutions:
like you suggested use view models to solve the problem. If you confirm the issue I can try to write example view model.
serialzie/encrypt entier Document in your view and next merge edited result with encrypted Document. You can achive that by using Mvc3Futures feature.
Serialize and encrypt your document in view:
#Html.Serialize("Document", Model, SerializationMode.EncryptedAndSigned)
And to deserialzie and decrypt you can use:
public ActionResult Edit(string id,[Deserialize(SerializationMode.EncryptedAndSigned)]Document document)

MVC ModelState and EntityFramework Validation

I have a edmx model done by Database First and generating the DBSet with the VS tools. I extended with partials the classes to add dataannotation validation to it.
I am receiving on my controller the view model which I am manually controlling the validation of fields. So eventhough I have a required field on my partial class, I am removing it once in my controller ModelState.Remove("pasajeros[" + count + "].numResidencia"); because of some conditions.
Before, I was using LINQTOSQL and I had no problems. But now Entity framework is not honoring my customization of ModelState.
How do i propagate or GO about this issue with EntityFramework?
thanks
Keep your view models and Entity models separate. Put your validation annotations on your view models. Then use a tool like Automapper to map the Entity to ViewModel fields for you.
On edit you validate your view model then update your Entity fields which you then save.

Data Annotations and MVC 4

I did MVC 2 two years ago. I am now using MVC 4 and would like to confirm a few things.
1) In MVC 4, we do not need to create a ModelMetadata class to annotate with data annotations for data validation. We may simply annotate the model classes themselves.
In other words, if we are using the EDM generator to generate a model and corresponding classes for us, then we may create a new set of partial classes with the same names and use data annotation attributes on those partial classes themselves.
We do not need to create a new type of model metadata class and decorate that class with data annotation/attributes, like here: http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validation-with-the-data-annotation-validators-cs
2) For data annotations to work, we need a reference only to System.ComponentModel.DataAnnotations and not to Microsoft.Web.Mvc.DataAnnotations.
3) We do not need to instantiate the default model binder in the Application_Start event in the Global.asax file.
Could you please confirm if my understanding is correct?
As I remember, there's no difference between MVC 2 and MVC 4 when it comes to this. You didn't have to use MetadataType in MVC 2, you could have used partial classes for generated models.
I'm not able to find any MSDN doc on Microsoft.Web.Mvc.DataAnnotations, but for data annotations to work with MVC you'd need System.ComponentModel.DataAnnotations and System.Web.Mvc (it contains some additional attributes like HiddenInputAttribute).
No, you don't, it's instantiated by framework.
Actually, for question 1, you need to use Metadata classes to annotate the properties of of model-first EF classes in the same way as previously with MVC2. When you use code-first EF classes, you can annotate them directly - the annotations will be used for generating the database as well as for scaffolding the Views.

Model layer dependency on MVC attributes

We have an MVC3 project that uses nHibernate; there is a separate model project that contains all the model classes which is used by the repository and service layers. The models make use of data annotations like DisplayAttribute and RequiredAttribute from System.ComponentModel.DataAnnotations.
There are also attributes such as RemoteAttribute that are contained in System.Web.Mvc.
This of course means that the model project now has a dependency to a particular front end technology.
Assuming the solution could have other front ends what would be the best way to handle this dependency link?
RemoteAttribute does not belong in the model, since it specifies a controller/action to validate the property on the server, and the model shouldn't have knowledge of concepts like controller, action or route. The presentation layer depends on the model, not the other way around.
I would create a view model that inherits the model, overrides the property (must be virtual) and adds the RemoteAttribute. This way you can avoid duplication and mapping, although that's also an alternative.
To reduce dependency between database model and frontend technology, you can use special view model for validation qnd other front end actions in controller and put data from viewmodel to database entity after it.

Resources