Client Side validation in MVC 3 Database First - asp.net-mvc-3

If I add [Required] in my entity class then unobtrusive validation works fine.
[Required] is not added where I generate my entity class using database first(*.edmx).
If I manually add [Required] in my entity property, something like
[Required]
public int {get;set;}
[Required] will delete when I update my edmx.
So my question is how can I perform client side validation if I use database first in EF.

Create a partial class for your entity and use the MetadataType attribute. See example below:
[MetadataType(typeof(MyEntity.Metadata))]
public partial class MyEntity
{
private sealed class Metadata
{
[Required(ErrorMessage = "* required")]
public string MyRequiredField { get; set; }
}
// Add other similar properties here...
}
This class will be unaffected by changes in the designer generated code.

This is a question for ado.net team. I suppose that when you use database first EF your domain model inherits constraints of database because database design is master for your application logic.

Related

How to make single controller for two database classes - MVC3

I have two database classes as defined below:
public class TopDate
{
[Key]
public int DateId { get; set; }
public DateTime Date { get; set; }
}
public class TopSong
{
[Key]
public int SongId { get; set; }
public string Title { get; set; }
public int DateId { get; set; }
}
where DateId is foreign key to TopSong
I am creating a controller through which i can create, delete or edit these database values.
When i right click on controller class and add controller i can only select one of the two classes defined above. Is there a way to make 1 controller to handle database updates to both these tables on one page?
Error Image:
Your controller should not be dealing directly with domain objects (meaning those things that are directly associated with your database). Create a ViewModel that contains the properties that you need, use your service layer to populate the ViewModel and your controller will use that as the Model for its base. An example of your ViewModel could be something like the following given your description above:
public class MusicViewModel
{
public int SongId {get;set;}
public string Title {get;set;}
public IEnumerable<DateTime> TopDates {get;set;}
}
This view model would contain a list of all dates that a specific song was a Top Song.
The objects you showing (code) are database classes (so called domain objects).
What you need to do is to define a view model, a standard ASP MVC practice:
you define a class, that is tailored for specific view and only containing data relevant to that particular view. So you will have a view model for a view that will create a song, another that will update it etc.
Actually situation you describing is classical situation to use view models. Using domain objects in the views, however, is really really bad practice and prone to more problems than you want to deal with.
Hope this helps.

Giving error while creating partial class

I am developing MVC application in which , I am trying to create the partial class of class generated by MVC application lets say Location class.
Now I want to create the partial class of Location class in new class file.
The below class code is auto genrated by MVC of Location code.
namespace CRM
{
public partial class Location
{
public int Id { get; set; }
public string Name { get; set; }
public string Remark { get; set; }
}
}
I have added new class file which contain the partial class of above file
namespace CRMEntities.Partial_Class
{
public interface ILocation
{
[StringLength(50, ErrorMessage = "Region can accept maximum 50 characters.")]
string Region { get; set; }
[Key]
int Id { get; set; }
[Required]
string Name { get; set; }
string Remark { get; set; }
}
public partial class Location : ILocation
{
}
}
Its giving the below error...
CRMEntities.Partial_Class.Location' does not implement interface member 'CRMEntities.Partial_Class.ILocation.Name
First, you don't need to do this, what I understand is you are trying to do validation right? Think about, the object generated by EF is not ViewModel, they are domain model. Data annotation should be in View Model, not domain model.
Most of cases, often mis-use is to use domain model as view model, but it is not correct much. Because sometime, view models need more than one domain model to provide data for your UI.
So for separation of concerns, you need to define your View Model different with domain model.
Example: you have Location class, you need to add LocationViewModel class and put data annotation in here.
You can map manually or use AutoMapper for mapping bettween View Model and Domain Model.
Another solution is you can use Fluent Validation, with this way, needless to have more partial class just for validation.
You don't show the definition of ILocation in your question, but the error says that the Location.Name property is declared differently than the ILocation.Name member.
Edit: Your two partial classes appear to be in two different namespaces, hence they are actually two entirely different classes, not two parts of the same class. That would explain the compiler error.
Having said that, I do agree with the other answer (+1!) that you should do your UI validation on a view model instead.

POCO - if POCO means pure .net class with only properties, where i can write validations in MVC

Very new to POCO, find some google links but found many different stories.
Some connected with Entity framework, lazy loading etc. Some says its a pure .det class.
Atleast MSDN.
LINK FOR DEFINE POCO FROM MSDN:
msdn.microsoft.com/en-us/library/dd456872.aspx
I trust MSDN(a simple defination), and assume that it is a pure .NET Class.
Now let me come to the point.
IF it is pure .net class with only properties inside it than it is equilateral to "MODEL" in MVC.
example.
[Required(ErrorMessage = "Full Name required.")]
[StringLength(20, ErrorMessage = "Username must be under 20 chars.")]
public string UserName { get; set; }
[Required(ErrorMessage = "Email required.")]
[RegularExpression(".+#.+\\..+", ErrorMessage = "Email not valid.")]
public string Email { get; set; }
[Required(ErrorMessage = "PassWord required.")]
[StringLength(20, ErrorMessage = "Maximum 20 chars. allow")]
[DataType(DataType.Password)]
public string Password { get; set; }
Upto this level it is clear to me. Now if i want to write my own validation (conditional) in MODEL
using
ValidationAttribute
or
IValidatableObject
this will be not pure .net class if i am not wrong.
example.... (Something like below)
public class Wizard : ValidationAttribute,IValidatableObject
{
public override bool IsValid(object value)
{
return base.IsValid(value);
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
throw new NotImplementedException();
}
[Required(ErrorMessage = "Full Name required.")]
[StringLength(20, ErrorMessage = "Username must be under 20 chars.")]
public string UserName { get; set; }
[Required(ErrorMessage = "Email required.")]
[RegularExpression(".+#.+\\..+", ErrorMessage = "Email not valid.")]
public string Email { get; set; }
[Required(ErrorMessage = "PassWord required.")]
[StringLength(20, ErrorMessage = "Maximum 20 chars. allow")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
Is this the POCO still?
If yes, how can it contains methods.(opposite to MSDN link)
IF NO, where should i write down my validation code (of course conditional validation in MVC).
Looking for a really great answer with an example.
POCOs mean you do not have to inherit from some framework defined base class in order to implement functionality. Basically you are free to design your class hierarchy.
You can add your own methods be it validation or some business logic.
A counter example would be to inherit from EntityObject class for entities in Entity Framework.
The linked article doesn't say that POCO mustn't have methods. Clear description what POCO is can be found on Wikipedia:
... the term is used to contrast a simple object with one that is
designed to be used with a complicated, special object frameworks such
as an ORM component. Another way to put it is that POCOs are objects
unencumbered with inheritance or attributes needed for specific
frameworks.
POCO can have all methods or logic you need. The difference between POCO and non-POCO is that POCO is class you can use always even if you don't use specific framework (EF) but non-POCO can be used only when specific framework is linked or even worse initialized and used.
For purists data annotations violates POCO as well because they also demand specific API but in pragmatic approach data annotations are OK (except special annotations used in EF Code first to define mapping) because they bring dependency only to the way how entity is validated but not the dependency to the way how entity is persisted (non-POCO EF object). Dependency on persistence can demand reference to EF in assemblies where you never expect to use EF - for example presentation layer like MVC application.
Personally I like to make my POCOs partial classes with the basic properties needed to define that model and then put and validation logic in a separate class. e.g:
public partial class Wizard
{
public string UserName { get; set; }
public string EmailAddress { get; set; }
}
and then if I wanted to add validation to UserName:
public partial class Wizard
{
[Required]
[StringLength(20)]
public string UserName { get; set; }
}
I know the complier just amalgamates the two classes anyway and you may be repeating properties but I think its the cleanest approach.
Another option is to use the MetadataType attribute.

mvc3 validation when using buddy classes

I am working on an mvc3 application and having some problems with getting validation to work as I want.
The application is using buddy classes for the models. (This is something I haven't used in the past and I am a little confused why they are used...anyway)
I want to add required fields to ensure data been submitted is correct. I have tried adding the required field to the buddy class.
When I submit the form no client-side validation takes place and the debugger steps into the entity frameworks generated code. Here is complains that the fields that contain null values are causing are invalid. If I step through all of those it finally gets to the controller where my if (ModelState.IsValid) is showing false.
I have client-side validation switched on.
Am I meant to be applying the data validation at the buddy class level or at the view model?
One other question is why use buddy classes? to me they seem to over complicate things.
Updated added an example of the buddy class
[MetadataType(typeof (CustomerMetaData))]
public partial class Customer
{
public string Priorty
{
get
{
var desc = (Priority) Priority;
return desc.ToString().Replace('_', ' ');
}
}
internal class CustomerMetaData
{
[Required]
[DisplayName("Priorty")]
public string Priorty { get; set; }
Buddy classes are metadata classes to put data annotation attributes when you are not in control of the original class i.e. can't edit it. Typical situation is when the class is generated by an ORM like Entity Framework.
//Can't edit this class
public partial class YourClass{
public string SomeField {get; set;}
}
//Add a partial class
[MetadataType(typeof(YourClassMetadata))]
public partial class YourClass{
}
//And a metadata class
public class YourClassMetadata
{
[Required(ErrorMessage = "Some Field is required")]
public string SomeField {get; set;}
}
are you sure that you have [MetadataType(typeof(YourClassMetadata))]?
More about buddy classes here and here
You would typically use a buddy class when it isn't possible to add meta data to an entity class such as when a model is automatically generated by an ORM tool. In this case any meta data you had applied would be lost.
Therefore, your original (automatically generated) class would be defined as a partial class:
public partial class Customer
{
public string Priority { get; set; }
}
And then you would generate your buddy classes to add the meta data.
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
}
internal class CustomerMetaData
{
[Required]
public string Priority { get; set; }
}
You would then pass the Customer class to the view where the Priority would be set.
In your case i'm not sure if you only have one partial class or two (as the other is not shown but please provide if there is). I'm interested to know how you obtain the priority information from the customer as i'm wondering if this is an issue with how you use ModelState.IsValid? The reason I ask is that no set accessor is declared on the Priority property so i'm wondering how this is set from the view in order to report that it is not valid?
You would also use a buddy class when it isn't possible to add meta data to an entity class such as when a model is automatically generated by an WCF Data Contract.

Using UIHint in combination with LINQ to SQL generated class

I used LINQ to SQL to generate a dbml file which contains the database model for my database table. I want to use UIHint to let MVC present some fields as DropDownLists or Checkboxes in edit mode. But if I change the file, it will be lost if it's been regenerated. How should I solve that issue? I'm quite new to MVC and still learning. I've set up a controller with views for all CRUD elements, but now I'm finetuning and I'm running into this problem.
Since Linq-to-SQL auto-generates partial classes, you'll need to create a partial 'buddy class' where you will add your Data Annotations. Your buddy class mirrors portions of the auto-generated class that you need to modify. You tie them together with [MetadataType(typeof(BuddyClassName))] The partial buddy class and the auto-generated partial class will be merged together when you compile your project.
In an example given that:
Your namespace is "Project.Models"
Your Linq-To-Sql class is called "Products"
using System.ComponentModel.DataAnnotations;
namespace Project.Models
{
[MetadataType(typeof(ProductsMeta))]
public partial class Products
{
// You can extend the products class here if desired.
public class ProductsMeta
{
// This is a Linq-to-Sql Buddy Class
// In here you can add DataAnnotations to the auto-generated partial class
[Key]
public int ProductKey { get; set; }
[Display (Name = "Product Name")]
[Required(ErrorMessage = "Product Name Required")]
[StringLength(255, ErrorMessage = "Must be under 255 characters")]
public string ProductName { get; set; }
[UIHint("MultilineText")]
public string Description { get; set; }
}
}
}
These articles were very helpful:
ScottGu: ASP.NET MVC 2: Model Validation
How to: Validate Model Data Using DataAnnotations Attributes
Validating with Data Annotation Validators
If you are going to use the entities directly you should create a partial class and add your annotations there. This way when the model is regenerated you will not lose your annotations.

Resources