Follow by Email

Friday, December 5, 2014

asp.net mvc validations using dataannotations

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

1. first create a model :
public class DataForm
{
[Key]
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;
_1


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();
}
[HttpPost]
public ActionResult data(DataForm d1) // will handle postback requests
{
if (ModelState.IsValid)
{
return RedirectToAction(“saveData”);
}
return View(d1);
}

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

1
@model mvcFilters.DataForm
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>data</title>
</head>
<body>
<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()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>DataForm</legend>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPNAME)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPNAME)
@Html.ValidationMessageFor(model => model.EMPNAME)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPADD)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPADD)
@Html.ValidationMessageFor(model => model.EMPADD)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPSAL)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPSAL)
@Html.ValidationMessageFor(model => model.EMPSAL)
</div>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}
<div>
@Html.ActionLink(“Back to List”, “Index”)
</div>
</body>
</html>
now run the project to check if the validations are working properly.
output:
2