Click here to Skip to main content
Click here to Skip to main content

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.

Introduction

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"> 
     UserComment 
    </asp:Content> 
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <h2>User Comment</h2> 
    <p><%=Html.ValidationSummary()%></p> 
    <% using (Html.BeginForm("UserComment","UserComment", FormMethod.Post)) { %> 
    <table border="0" cellpadding="2" cellspacing="0"> 
    <tr> 
    <td>Name:</td> 
    <td> 
    <%=Html.TextBox("name", ViewData["name"] ?? "")%> 
    <%=Html.ValidationMessage("name")%> 
    </td> 
    </tr> 
    <tr> 
    <td>Email:</td> 
    <td> 
    <%=Html.TextBox("email", ViewData["email"] ?? "")%> 
    <%=Html.ValidationMessage("email")%> 
    </td> 
    </tr> 
    <tr> 
    <td colspan="2">Comment:</td> 
    </tr> 
    <tr> 
    <td colspan="2"> 
    <%=Html.TextArea("Comment", ViewData["Comment"] ?? "")%> 
    </td> 
    </tr> 
    <tr> 
    <td colspan="2"> 
    <%=Html.ValidationMessage("Comment")%> 
    </td> 
    </tr> 
    <tr> 
    <td> </td> 
    <td> 
    <input type="submit" value="Submit your commit" /> 
    </td> 
    </tr> 
    </table> 
    <% } %> 
    </asp:Content>
  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 
    { 
        [AcceptVerbs("GET")] 
        public ActionResult UserComment() 
        { 
            return View(); 
        } 
        [AcceptVerbs("POST")] 
        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:

Summary

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.

License

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) http://www.Fairnet.com
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.

Comments and Discussions

 
GeneralMy vote of 3 PingroupKikoz6830-Aug-11 14:46 
GeneralHow to retain values??? PinmemberHiteshforu200716-Jun-11 20:37 
GeneralNice Article PinmemberJithu Jose26-Nov-10 5:53 

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

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

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