Wednesday 7 October 2015

Validation in MVC


One of the easy ways of doing validation in MVC is by using data annotations.

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 “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 “ModelState.IsValid” property and accordingly we can take actions.


We can use “ValidationSummary” method from HTML helper class to display validation message at one go.


No comments:

Post a Comment