Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Form validation with ASP.NET MVC

4.60/5 (2 votes)
16 Aug 2009CPOL1 min read 68.3K  
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. Image 1

  3. Add the following code in the UserComment.aspx view:
  4. ASP.NET
    <%@ 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>
  5. Select the "Controllers" folder and then right click and click on Controller as shown below:
  6. Image 2

  7. Add the following code in the UserComment.cs controller:
  8. C#
    [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(); 
        } 
    }
  9. Now you can run the project and it will display the user comment view as shown below:
  10. Image 3

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)