In this article I will explain with an example, how to implement HTML5 validation in ASP.Net MVC.
Validation will be performed by setting HTML5 required attribute in TextBox using HTML.TextBoxFor and HTML.TextBox helper methods in ASP.Net MVC.
Model
The Model class consists of following property.
public class PersonModel
{
///<summary>
/// Gets or sets Name.
///</summary>
public string Name { get; set; }
}
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, an object of PersonModel class is created where Name property value is set and is returned to the View. The value of the Name property will be set in the TextBox created using Html.TextBoxFor and Html.TextBox helper methods.
Action method for handling POST operation
Inside this Action method, the View is redirected to Index view.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
PersonModel person = new PersonModel
{
Name = "Mudassar Khan"
};
return View(person);
}
[HttpPost]
public ActionResult Submit()
{
return View("Index");
}
}
View
HTML Markup
Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View consists of two HTML INPUT TextBoxes created using Html.TextBoxFor and Html.TextBox Html helper methods.
Html.TextBoxFor
The TextBox created using Html.TextBoxFor is set with following properties:
model property – The name of the property is set using Lambda expression.
htmlAttributes – An object that contains the HTML attributes to set for the element. In this case it is required.
Html.TextBox
The TextBox created using Html.TextBox is set with following properties:
name – The name of the form field. In Controller the TextBox value is captured using this parameter.
value– The value of the text input element.
htmlAttributes – An object that contains the HTML attributes to set for the element. In this case it is required.
@model TextBox_Required_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
@Html.TextBoxFor(m => m.Name, new { @required = "required" })
<br/><br/>
@Html.TextBox("Country", "", new { @required = "required" })
<br /><br />
<input type="submit" value="Submit" />
}
</body>
</html>
Screenshot
Rendered Page
Downloads