One of the easiest ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties. For example, in the below code snippet we have a simple Customer
class with a property customercode
.
This CustomerCode
property is tagged with a Required
data annotation attribute. In other words if this model is not provided customer code, it will not accept it.
public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
In order to display the validation error message we need to use the ValidateMessageFor
method which belongs to the Html
helper class.
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>
Later in the controller we can check if the model is proper or not by using the ModelState.IsValid
property and accordingly we can take actions.
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Below is a simple view of how the error message is displayed on the view.