Follow by Email

Friday, December 5, 2014 mvc validations using dataannotations

hi lets see how to do validation in mvc using dataannotations
so lets start implementing this.

1. first create a model :
public class DataForm
public int EMPID { get; set; }
[StringLength(60, MinimumLength = 3,ErrorMessage=”Min String length is 3″)]
public string EMPNAME { get; set; }
[Required(ErrorMessage=”Field should not be empty”)]
public string EMPADD { get; set; }
[RegularExpression(@”^[0-9]{0,8}$”, ErrorMessage = “Salary should be Numeric”)]
public string EMPSAL { get; set; }
here in the above model we will define the form fields and the validation messages. we also need to add below namespace
using System.ComponentModel.DataAnnotations;

2. after this go to controller and add two action methods.
httppost action method will only accept the postback requests like the submit, create.
public ActionResult data() // will be called intially
return View();
public ActionResult data(DataForm d1) // will handle postback requests
if (ModelState.IsValid)
return RedirectToAction(“saveData”);
return View(d1);

3. now add a strongly typed view using model DataForm and using scaffold template as create.

@model mvcFilters.DataForm
Layout = null;
<!DOCTYPE html>
<meta name=”viewport” content=”width=device-width” />
<script src=”~/Scripts/jquery-1.8.2.min.js”></script>
<script src=”~/Scripts/jquery.validate.min.js”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js”></script>
@using (Html.BeginForm()) {
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPNAME)
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPNAME)
@Html.ValidationMessageFor(model => model.EMPNAME)
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPADD)
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPADD)
@Html.ValidationMessageFor(model => model.EMPADD)
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPSAL)
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPSAL)
@Html.ValidationMessageFor(model => model.EMPSAL)
<input type=”submit” value=”Create” />
@Html.ActionLink(“Back to List”, “Index”)
now run the project to check if the validations are working properly.