ASP.NET MVC3 Generate View Model including validation attributes - asp.net

I am wondering if there is a way to generate a View Model from database table including validation (required,length,datatype). Of course I will edit it and enhance it.Otherwise it is a waste as I have to type in everything

We are implementing a "Dynamic" approach to validation in one of our projects where the validation rules are encoded in a database table and we override GetValidators() in a custom implementation of DataAnnotationsModelValidatorProvider to inject custom and/or standard validation attributes. These can then be propagated to the client if we want them to. As for creating a viewModel from the existing database, you can use t4 files to read the db schema and generate classes for you and inject validation attributes on the model as it is being created.

Related

Customizing data annotation attributes for ASP.NET MVC

I would like to customize at runtime the attributes that MVC sees on a view model property. As far as I know, MVC relies internally on type descriptors to enumerate the attributes. Is there a way to hook a type descriptor somewhere to return a custom list of attributes for a property?
Is there a way to hook a type descriptor somewhere to return a custom
list of attributes for a property?
It depends. If you want to override the Data Annotations used by the metadata provider then you could write your own custom ModelMetadataProvider and replace the default one (DataAnnotationsModelMetadataProvider). This allows you to have a custom metadata provider for a given type and return this information at runtime.
If on the other hand you are doing validation, then you are a bit out of luck. For more flexibility I would recommend you using FluentValidation.NET instead of data annotations.

Domain logic in a Entity framework Attribute

I've an ASP.NET MVC project with a domain and a data layer (contains just EF and migrations).
Now, I have to validate a Client's VATNumber field with a specific formula I'm having doubts where to place it.
I would like to use the Controller's ModelState to check if the field is valid, using a EF DataAnnotation ValidationAttribute, so I don't have to validate it in the Controller's Saving Method. But I'm conflicted having to put business logic in the data layer.
Is there some kind of alternative to ValidationAttribute, so it can be "injected"? Or I'm just looking at this wrongly?
Validation attributes is not part of Entity Framework.
If you want splite data layer from presentation layer, you can use Viewmodels and bind them on datamodels with Automapper. In this case you place domain validation on viewmodel and validation of datalayer on datamodel.
In very complicated cases you may have three models: viewmodel, domainmodel and datamodel, but in common cases viewmodel and datamodel is enough.

Do standard ASP.NET controls connected to an entity datasource provide built in validation?

The entity framework connects to my database to retrieve columns, datatypes, relations, etc. It also knows which columns can be null and not null.
If I connect a regular asp.net grid to an entity datasource, it can generate the grid automatically based on the entity. It knows which fields should be a checkbox based on the datatype, etc.
Since data types are built into the entity class, can a regular asp.net control (like a grid or formview) also perform validation automatically? (or generate the necessary validation controls at least?)
Thanks,
Kevin
Yes, you can display validation errors including validation types using asp:ValidationSummary control. Here one project with this approach used on gridview: http://code.msdn.microsoft.com/ASPNET-Web-Forms-97f8ee9a , check out editing students.
The way to add more validation rules to entities is by attaching meta data.
If you are using EF Code First you can apply rules directly else by adding meta data class, here example:
[MetadataType(typeof(EntityNameMetaData))]
public partial class EntityName {} // name of entity which want to add validation
public class EntityNameMetaData // this is a place, where put validation rules
{
[StringLength(25, ErrorMessage = "First name must be 25 characters or less in length.")]
[Required(ErrorMessage = "First name is required.")]]
//custom or other validation rules
public String EntityProperty
}
this is not possible automatically in asp.net, you would have to define the columns and create item templates to implement this.

Why we create Entity/Enquiry.php And Form/EnquiryType.php In Seperate Folders Symfony2?

Going through the Symblog tutorial of Symfony2, While creating forms I came to a point where in I create Contact Entity (Entity/Enquiry.php) where I define some fields and some methods to access these fields. Then I create another folder Form/EnquiryType.php to build the form and then a contact.html.twig to display. I am unable to understand why we created 2 namespaces for Entity/Enquiry.php and Form/EnquiryType.php. when they have to deal with each other. Why dont we wrote both the classes within one folder or one file. And one more question. Do they belong to Controller or View part of MVC.
Form types are here to configure how data coming from objects (like Entities) are mapped to a form (and vice/versa).
Entities should'nt be named "entities", they should be just your buisness objects, that can be persisted through a layer called doctrine2.
To answer you on separation of concerns,
Entities are about M,
while form Types are about user inputs (so the VC).
View because it render a human interface to let user enter input,
Controller because that's where you handle the form lifecycle.
The reason is logical separation. Why don't we define all parts of MVC in one folder/namespace? Because it will be a mess. That's why logical separation is needed.
And not all entities have to have related form types — using entities without forms is normal.

asp.net mvc3 / razor view best practices

I am using in my views (asp mvc3/razor cshtml) references to the Request object (eg, #Request.Params["Name"]). Do you think this is a very bad practice? Should I rewrite the value in the controller Request.Params ["Name"] to ViewBag.Name and then use it in the view (#ViewBag.Name)?
Best practice is to use a model class. An instance of the model class is created or updated in your controller. Then the controller displays a strongly-typed view.
So I'd avoid direct access to the request from the view as well as the use of the view bag.
Should I rewrite the value in the controller Request.Params ["Name"] to ViewBag.Name and then use it in the view (#ViewBag.Name)?
Yes. You will avoid runtime errors if "Name" does not exist.
The IDE will not warn you of the NullReferenceException about to be thrown with the following code.
#Request.Params["Fake"].ToString()
Of course, you'll have to be careful about ViewBag.Fake being null as well.
I like to use the viewbag to store things not related to the model, for example if I have a dropdown containing locations. I like to store only the id of the selected location on the model and the locations in the viewbag, since is not needed to create a contact. I think that's the purpose of the viewbag.
For me the model is a bag or properties used in business operations, for example if I have a customer creation view using a NewCustomerModel, I don't wanna pollute my model with things like a IList<CustomerType> AND a SelectedCustomerTypeId property. I just want the second since is the one imma use to create the customer.

Resources