This
topic contains a brief description about ASP.NET MVC. If you are looking for
ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC
site.
Abstract:
Validation is one of the most important aspects of an application.
ASP.NET MVC framework provides multiple ways to validate the user input. In
this article we are going to demonstrate how to perform validation in an
ASP.NET application using Controller action, IDataErrorInfo and DataAnnotations
methods.
Simple Validation:
The most simple way to perform validation is to perform it inside the
Controller. The controller will be responsible for checking for the validity of
the data. Let's check out the code for the view.
<asp:Content ID="Content2"
ContentPlaceHolderID="MainContent" runat="server">
<h2>Simple Validation</h2>
<% using (var form = Html.BeginForm(new { Action =
"SimpleValidation" }))
{ %>
FirstName: <%= Html.TextBox("FirstName")%>
LastName: <%= Html.TextBox("LastName")%>
<input type="submit" value="Save"
/>
<% } %>
</asp:Content>
As, you can see the view is very simple and consists of FirstName and LastName
TextBoxes. The submit button will submit the form and invoke the "SimpleValidation"
action of the controller.
The controller used in this case is the HomeController. The SimpleValidation
action is responsible for performing the validation on the data. The
implementation of the SimpleValidation action is shown below:
public ActionResult SimpleValidation(Customer customer)
{
if(String.IsNullOrEmpty(customer.FirstName))
ModelState.AddModelError("FirstName","FirstName cannot be
blank!");
if(String.IsNullOrEmpty(customer.LastName))
ModelState.AddModelError("LastName","LastName cannot be
blank!");
if
(!ModelState.IsValid)
return View("SimpleValidation");
return
View("Confirmation");
}
The SimpleValidation action accepts the Customer object as an input parameter.
This is performed by Model Binders feature in ASP.NET MVC framework.
Inside the SimpleValidation action the ModelState.AddModelError method is used
to populate the error collection of the model. The ModelState.IsValid property
represents if there are any errors in the model. If the model is invalid then
we simply return the current view which in this case is "SimpleValidation".
If the model is valid then we return the "Confirmation" view.
Finally, make the adjustments in the view to display the errors. This is
performed by the HTML helpers ValidationMessage as shown below:
<asp:Content ID="Content2"
ContentPlaceHolderID="MainContent" runat="server">
<h2>Simple Validation</h2>
<% using (var form = Html.BeginForm(new { Action =
"SimpleValidation" }))
{ %>
FirstName: <%= Html.TextBox("FirstName")%>
<%= Html.ValidationMessage("FirstName","*")
%>
LastName: <%= Html.TextBox("LastName")%>
<%=
Html.ValidationMessage("LastName","*") %>
<input type="submit" value="Save"
/>
<% } %>
</asp:Content>
Now, run the above page and click on the "submit" page without
inputting the values for the FirstName and LastName. You will realize that the
page was not submitted successfully since it was invalid. You can even make the
errors more visible by using the ValidationSummary HTML helper as shown below:
<% using (var form = Html.BeginForm(new { Action =
"SimpleValidation" }))
{ %>
<%= Html.ValidationSummary("Errors")
%>
FirstName: <%= Html.TextBox("FirstName")%>
<%= Html.ValidationMessage("FirstName","*")
%>
LastName: <%= Html.TextBox("LastName")%>
<%=
Html.ValidationMessage("LastName","*") %>
<input type="submit" value="Save"
/>
<% } %>
Validation Using IDataErrorInfo:
The second method of performing validation in an ASP.NET MVC application
is by using the IDataErrorInfo class. This method involves the model class to
inherit from the IDataErrorInfo interface. The implementation is shown below:
public class Customer : IDataErrorInfo
{
private string _firstName;
private string _lastName;
private
Dictionary<String,String> _errors = new Dictionary<string,
string>();
public string FirstName
{
get { return
_firstName; }
set
{
if(String.IsNullOrEmpty(value))
_errors.Add("FirstName","FirstName cannot be blank!");
_firstName = value;
}
}
public string LastName
{
get { return
_lastName; }
set
{
if(String.IsNullOrEmpty(value))
_errors.Add("LastName","LastName cannot be blank!");
_lastName = value;
}
}
public string this[string
columnName]
{
get
{
if (_errors.ContainsKey(columnName))
return _errors[columnName];
return String.Empty;
}
}
public string Error
{
get { return
String.Empty; }
}
}
Using this method the controller action is simplified as the validation is now
moved into the model itself. The implementation is shown below:
public ActionResult ValidationUsingIDataErrorInfo(Customer customer)
{
if
(!ModelState.IsValid)
return View("ValidationUsingIDataErrorInfo");
return
View("Confirmation");
}
Using DataAnnotations:
The DataAnnotations provides the most easiest way to perform validation
in an ASP.NET MVC application. It uses attributes to perform validation.
You need to download "Data Annotations Model Binder Sample". Once, it
is downloaded you need to build the solution in Visual Studio which will create
the "Microsoft.Web.Mvc.DataAnnotations" and System.ComponentModel.DataAnnotations"
assemblies. The final step is to set the DataAnnotations default binder to the
Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder(); in the
Global.asax file as shown below:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.DefaultBinder = new
Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
}
Now, in order to use the validation you will simply use the attributes on the
model properties as shown below:
public class Customer
{
[Required(ErrorMessage =
"FirstName cannot be blank")]
public string FirstName { get; set;
}
[Required(ErrorMessage
="LastName cannot be blank!")]
public string LastName { get; set; }
}
Top Reasons to trust your
ASP.NET MVC website to ASPHostCentral.com
What we think makes ASPHostCentral.com
so compelling is how deeply integrated all the pieces are. We integrate and
centralize everything--from the systems to the control panel software to the
process of buying a domain name. For us, that means we can innovate literally
everywhere. We've put the guys who develop the software and the admins who
watch over the server right next to the 24-hour Fanatical Support team, so we
all learn from each other:
- 24/7-based Support - We never fall
asleep and we run a service that is operating 24/7 a year. Even everyone is on
holiday during Easter or Christmas/New Year, we are always behind our desk
serving our customers
- Excellent Uptime Rate - Our key
strength in delivering the service to you is to maintain our server uptime
rate. We never ever happy to see your site goes down and we truly understand
that it will hurt your onlines business. If your service is down, it will
certainly become our pain and we will certainly look for the right pill to kill
the pain ASAP
- High Performance and Reliable Server
- We never ever overload our server with tons of clients. We always load
balance our server to make sure we can deliver an excellent service, coupling
with the high performance and reliable server
- Experts in ASP.NET MVC Hosting -
Given the scale of our environment, we have recruited and developed some of the
best talent in the hosting technology that you are using. Our team is strong
because of the experience and talents of the individuals who make up
ASPHostCentral
- Daily Backup Service - We realise
that your website is very important to your business and hence, we never ever
forget to create a daily backup. Your database and website are backup every
night into a permanent remote tape drive to ensure that they are always safe
and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With
our powerful control panel, you can always administer most of your site
features easily without even needing to contact for our Support Team.
Additionally, you can also install more than 100 FREE applications directly via
our Control Panel in 1 minute!
Happy hosting!