articles

Home / DeveloperSection / Articles / Validation using Data Annotation using entity framework

Validation using Data Annotation using entity framework

Manish Kumar3658 19-Jan-2017

Data annotation is for adding extra meaning to the data. We use attribute for data annotation. There are many attribute which we use for data annotation. We use data annotation for data validating, we can validate our field by data annotation by simply adding attribute.

By data annotation we can validate our field in the UI and by using Display attribute we can specify that how data from model is displayed in view or UI. 

We use system.componentmodel.DataAnnotation namespace for using attribute of data annotation.

Now we will take an example for data annotation.

When we are working with data first approach. We cannot put our validation in the self-generate class from the EF because when we change our database table our validation will lose so the right way is For  data annotation to create a class in model folder and name it Metadata’s

using System;
using System.Collections.Generic;
using System.Linq;                           
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Demo.Models
{
    publicclassEmpDetailMetaData
    {
      
        [Required(ErrorMessage = "UserName Name is required")]
        publicstring UserName { get; set; }
        [Required(ErrorMessage = "FName Name is required")]
        publicstring FName { get; set; }
        [Required(ErrorMessage = "Email is required")]
        publicstring Email { get; set; }
        [Required(ErrorMessage = "Mobile is required")]
        publicstring Mobile { get; set; }
    }
}


And another class name it partialclass

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
 
namespace Demo.Models
{     
        [MetadataType(typeof(EmpDetailMetaData))]
        publicpartialclassEmpDetail
        {
        }
}


In the above metadata class we have use required attribute

Now in the controller we do the logic for validation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Demo.Models;
 
 
namespace Demo.Controllers
{
    publicclassHomeController : BaseController
    {                  publicActionResult Index()
        {
            ViewBag.Users = Uow.EmpDetail.SelectAll();      
           
            return View();
        }
 
    [AcceptVerbs(HttpVerbs.Post)]
        publicActionResult Index(EmpDetail model)
        {
            if (ModelState.IsValid)
            {
                if (model.Id == 0)
                {
                    Uow.EmpDetail.Insert(model);
 
                }
                else
                {
                    var data = Uow.EmpDetail.SelectByID(model.Id);
                    if (data == null)
                        Uow.EmpDetail.Insert(model);
                    else
                        Uow.EmpDetail.Update(model);
                }
            }
                ViewBag.Users =Uow.EmpDetail.SelectAll();
                return PartialView("UserList");          
         
        }             [HttpPost]
        publicActionResult Delete(int Id)
        {
            Uow.EmpDetail.Delete(Id);         
            ViewBag.Users = Uow.EmpDetail.SelectAll();           
            return PartialView("UserList");
        }     
        publicActionResult Edit(int Id)
        {
            var data = Uow.EmpDetail.SelectByID(Id);
            return Json(data, JsonRequestBehavior.AllowGet);
        }
      
 
    }
}
 

Now int the add view for for index method.
@{

    ViewBag.Title = "Index";
}
 
@*<script src="~/Scripts/jquery-3.1.1.min.js"></script> *@
<scriptsrc="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<scriptsrc="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<scriptsrc="~/Scripts/jquery.validate.min.js"></script>
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.2/jquery.validate.unobtrusive.js"></script>
@using (Ajax.BeginForm("index", "Home", newAjaxOptions
{
    HttpMethod = "POST"
    UpdateTargetId = "target",
    OnSuccess = "updateSuccess"
}))
{
 
        <center><h2>Registration Form</h2></center>
     @Html.ValidationSummary(true
        <hr/>
       <div>
            <center><tableborder="0"  width="70%"cellspadding="0"cellspacing="0">
        <tr>
             <td><labelid="label1">User Name</label>
                @Html.HiddenFor(x => x.Id, new {@Value=0 })
            </td>
              <td>@Html.TextBoxFor(x => x.UserName)
                  @Html.ValidationMessageFor(m => m.UserName)
              </td>
            <td><labelid="label2">Father Name</label></td>
              <td>@Html.TextBoxFor(x => x.FName)
                  @Html.ValidationMessageFor(m => m.FName)
              </td>
        </tr>
       <tr>
            <td><labelid="label3">Email</label></td>
              <td>@Html.TextBoxFor(x => x.Email)
                  @Html.ValidationMessageFor(m=> m.Email)
              </td>
            <td><labelid="label4">Mobile</label></td>
              <td>@Html.TextBoxFor(x=> x.Mobile)
                  @Html.ValidationMessageFor(m => m.Mobile)
              </td>
        </tr>
       <tr>
         <tdcolspan="2"><br/><center>
               <inputtype="submit"value="Submit"/></center>
           </td>
       </tr>
    </table></center>
        </div>
         
 
}

 

You can also visit these related articles and blogs

Crud operation in mvc using data annotation with entity framework

Upload File using Model Validation in ASP.NET MVC


Updated 17-Nov-2018

Leave Comment

Comments

Liked By