Wednesday, November 16, 2011

MVC validation by Data Annotation ---Razor view --- Entity Framework 4.1

1- create parial class with the same namespace of the original class that is generated with the Entity framework :
namespace myNamespace
{
[MetadataTypeAttribute(typeof(Metadata))]
public partial class MyClass
{
private class Metadata
{
[Required]
public object Property_1{ get; set; }
}
}
}
2-enable client validation in the view:
@{ Html.EnableClientValidation(); }
@using (Html.BeginForm())
{

}
3- add the validation controls :
@Html.ValidationMessage("Property_1","*") // where "Property_1" is the property name which need to be validated

4- modify the controller to handle the validation : for example in the action we provide 2 different pathes , one for isValid== true another for is valid == false:
for example:
if (ModelState.IsValid)
{
// do work
}
else
{
// another work
}

No comments: