Example Application on Data Annotations
Follow the below steps to work with the Data Annotations.
- Open a new MVC Application.
- Create a Model as shown in the below figures
- Then a new window will appear as shown in the below figure. Give the name as Employee.
- Write the following code under the Employee class in the model.
[csharp]
public class Employee
{
[Key]
public int EmpId { get; set; }
[Required(ErrorMessage="Please enter the EmpName")]
public string EmpName { get; set; }
[Required(ErrorMessage = "Please enter the EmpSalary")]
public int EmpSalary { get; set; }
[Required(ErrorMessage = "Please enter the EmpAddress")]
public string EmpAddress { get; set; }
[Required(ErrorMessage = "Please enter the EmpEmailId")]
[EmailAddress(ErrorMessage="Please enter the valid email id")]
public string EmpEmailId { get; set; }
[Required(ErrorMessage = "Please enter the EmpPhone")]
public string EmpPhone { get; set; }
}
[/csharp]
Remember
Make sure that the following namespace is added. Otherwise, you will get an error.
using System.ComponentModel.DataAnnotations;
Now add a view and write the following code.
[html]
@{
ViewBag.Title = "Employee";
}
<h2>Employee</h2>
@using (Html.BeginForm("Submit"))
{
<table>
<tr>
<td>@Html.Label("L1", "EmpId")</td>
<td>@Html.TextBox("T1")</td>
</tr>
<tr>
<td>@Html.Label("L2", "EmpName")</td>
<td>@Html.TextBox("T2")</td>
</tr>
<tr>
<td>@Html.Label("L3", "EmpSalary")</td>
<td>@Html.TextBox("T3")</td>
</tr>
<tr>
<td>@Html.Label("L4", "EmpAddress")</td>
<td>@Html.TextBox("T4")</td>
</tr>
<tr>
<td>@Html.Label("L5", "EmpEmail")</td>
<td>@Html.TextBox("T5")</td>
</tr>
<tr>
<td>@Html.Label("L6", "EmpPhone")</td>
<td>@Html.TextBox("T6")</td>
</tr>
</table>
<input type="submit" value="submit" />
}
[/html]
Now add a controller and give the name as
Employee and write the following code.
[csharp]
public ActionResult Employee()
{
return View();
}
[/csharp]
Run the application. The following window will appear.
Click on submit button. Then you will get error messages.