Click here to Skip to main content
13,004,812 members (66,224 online)
Click here to Skip to main content
Add your own
alternative version


13 bookmarked
Posted 16 Aug 2009

Form validation with ASP.NET MVC

, 16 Aug 2009
Rate this:
Please Sign up or sign in to vote.
This topic shows you the MVC features that support form validation.


This topic shows you the MVC features that support form validation. When a user submits a form, the form data is passed to a controller action method by using the ViewDataDictionary collection. The ViewDataDictionary has a ModelState property that contains a collection of ModelState objects. For each model that is defined in an MVC application, the MVC framework creates a corresponding ModelState object and adds it to the collection. The action method that receives the form data defines the validation rules that apply to the form data. If a rule is violated, the action method uses the ModelState property to pass the validation error information back to the view. You can then use HTML helper methods in the view to render a summary of error messages and indicate the form fields where errors are found. I will modify my previous project for form validation. Follow these steps to create a user comment sample:

  1. Select the "Views" and create a new folder UserComment, and then right click and add a view, as shown below:
  2. Add the following code in the UserComment.aspx view:
  3. <%@ Page Title="" Language="C#" 
       MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <h2>User Comment</h2> 
    <% using (Html.BeginForm("UserComment","UserComment", FormMethod.Post)) { %> 
    <table border="0" cellpadding="2" cellspacing="0"> 
    <%=Html.TextBox("name", ViewData["name"] ?? "")%> 
    <%=Html.TextBox("email", ViewData["email"] ?? "")%> 
    <td colspan="2">Comment:</td> 
    <td colspan="2"> 
    <%=Html.TextArea("Comment", ViewData["Comment"] ?? "")%> 
    <td colspan="2"> 
    <td> </td> 
    <input type="submit" value="Submit your commit" /> 
    <% } %> 
  4. Select the "Controllers" folder and then right click and click on Controller as shown below:
  5. Add the following code in the UserComment.cs controller:
  6. [HandleError] 
    public class UserCommentController : Controller 
        public ActionResult UserComment() 
            return View(); 
        public ActionResult UserComment(string name, string email, string comment) 
            ViewData["name"] = name; 
            ViewData["email"] = email; 
            ViewData["message"] = comment; 
            if (string.IsNullOrEmpty(name)) 
                ModelState.AddModelError("name", "Please enter your name!"); 
            if (!string.IsNullOrEmpty(email) || !email.Contains("@")) 
                ModelState.AddModelError("email", "Please enter a valid e-mail!"); 
            if (string.IsNullOrEmpty(comment)) 
                ModelState.AddModelError("comment", "Please enter a comment!"); 
            if (ViewData.ModelState.IsValid) 
                // Save to Database 
            return View(); 
  7. Now you can run the project and it will display the user comment view as shown below:


In this article, we explored form validation with ASP.NET MVC by creating a user comment view. In the next article, I will explore custom HTML helpers in the ASP.NET MVC framework.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Farooq Kaiser
Software Developer (Senior)
Canada Canada
12+ years of complete software development life cycle experience for web based applications and multi-tier client-server desktop, primarily using LINQ, WCF, WWF, C#, ASP.NET, XML, XSLT, AJAX, Winforms,Visual Basic, JavaScript, JQuery, Google APIs, C++, VB.NET, C, ATL/COM, Open XML. Extensively involved in the requirement analysis, feasibility study, conceptualization, planning, architecture/design, configuration, development, quality assurance, implementation and release of the software products.

You may also be interested in...

Comments and Discussions

QuestionWhat is the use of ?? in ViewData Pin
aniruddhamca8-Dec-15 0:27
memberaniruddhamca8-Dec-15 0:27 
AnswerRe: What is the use of ?? in ViewData Pin
Raje_8-Dec-15 0:36
memberRaje_8-Dec-15 0:36 
GeneralMy vote of 3 Pin
Kikoz6830-Aug-11 14:46
groupKikoz6830-Aug-11 14:46 
GeneralHow to retain values??? Pin
Hiteshforu200716-Jun-11 20:37
memberHiteshforu200716-Jun-11 20:37 
GeneralNice Article Pin
Jithu Jose26-Nov-10 5:53
memberJithu Jose26-Nov-10 5:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170627.1 | Last Updated 16 Aug 2009
Article Copyright 2009 by Farooq Kaiser
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid