There are two ways to add custom validations in MVC 4:
- Using Data Annotations with Model Binder.
- Using Data Annotations in Entity Framework.
Let us see:
- Using Data Annotations with Model Binder
Inorder to use DataAnnotation with Model Binder, you need to add references to the following dlls:
You also need to register the DataAnnotations Model Binder in the Global.asax file. Add the following line of code to the Application_Start() event handler so that the Application_Start() method looks like this:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.DefaultBinder = new
Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
}
Inside your Model, Create a class named as TerritoryModel.
public class TerritoryModel:DistributionEntities
{
}
Now, create a constructor that should again inherit from
:base(Your Model Context Name)
.public class TerritoryModel:DistributionEntities
{
public TerritoryModel:base("DistributionEntities")
{
}
}
public DbSet<districtmaster> districts{ get; set; }
DbSet is a class that represent the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from the a DbContext using the DbContext.SetMethod
Now create a class called DistrictMaster and bind it with your database table by providing [Table("District")] attribute at the top of this class.
This class is as:
public class DistricMaster
{
}
This class is as:
public class DistricMaster
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DistrictId { get; set; }
[Required(ErrorMessage="Please select State Name for entering the district.")]
[Display(Name = "State Name")]
public string StateId { get; set; }
[Required(ErrorMessage="Please enter District Name.")]
[StringLength(50,ErrorMessage="Please enter atleast {0}
characters.",MinimumLength=2)]
[Display(Name = "District Name ")]
public string DistrictName { get; set; }
}
Thats all. You are done.
The complete model class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Distribution.Entities;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Distribution.Web.Models
{
public class TerritoryModel:DistributionEntities
{
public TerritoryModel():base("DistributionEntities")
{
}
public DbSet<districtmaster> districts { get; set; }
}
[Table("District")]
public class DistrictMaster
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DistrictId { get; set; }
[Required(ErrorMessage="Please select State Name for entering the district.")]
[Display(Name = "State Name")]
public string StateId { get; set; }
[Required(ErrorMessage="Please enter District Name.")]
[StringLength(50,ErrorMessage="Please enter atleast {0}
characters.",MinimumLength=2)]
[Display(Name = "District Name ")]
public string DistrictName { get; set; }
}
}
Now let us have a look at validations using second method.
- Using DataAnnotations Validators with Entity Frame Work.
If you are using the Microsoft Entity Framework to generate your data model classes then you cannot apply the validator attributes directly to your classes. Because the Entity Framework Designer generates the model classes, any changes you make to the model classes will be overwritten the next time you make any changes in the Designer.
If you want to use the validators with the classes generated by the Entity Framework then you need to create meta data classes. You apply the validators to the meta data class instead of applying the validators to the actual class.
Consider the example above for the District class using the Entity Framework (see figure below.). Imagine, furthermore, that you want to make both the properties i.e., State and District Name as required properties. In that case, you can create the partial class and meta data class.
So, your coding is as: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Distribution.Entities
{
[MetadataType(typeof(DistrictMetaData))]
public partial class District
{
}
public class DistrictMetaData
{
[Required(ErrorMessage = "Please select State Name for entering the
district.")]
[Display(Name = "State Name")]
public string StateId { get; set; }
[Required(ErrorMessage = "Please enter District Name.")]
[StringLength(50, ErrorMessage = "Please enter atleast {0} characters.",
MinimumLength = 2)]
[Display(Name = "District Name ")]
public string DistrictName { get; set; }
}
}
CONCLUSION
So, we have seen validations in MVC4 using two different ways.
FEEDBACK
Hope the post will be useful for you in your programming career. What I need from you is to comment below and share with me your doubts and/or suggestions. If you have any other way of doing the same, then please do comment. Thank you :) Have a wonderful programming.
No comments:
Post a Comment