Click here to Skip to main content
15,881,709 members
Articles / Web Development / ASP.NET

Form validation with ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.60/5 (2 votes)
16 Aug 2009CPOL1 min read 67.7K   13   5
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)


Written By
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhat is the use of ?? in ViewData Pin
aniruddhamca8-Dec-15 0:27
aniruddhamca8-Dec-15 0:27 
AnswerRe: What is the use of ?? in ViewData Pin
Raje_8-Dec-15 0:36
Raje_8-Dec-15 0:36 
GeneralMy vote of 3 Pin
Kikoz6830-Aug-11 14:46
Kikoz6830-Aug-11 14:46 
GeneralHow to retain values??? Pin
Hiteshforu200716-Jun-11 20:37
Hiteshforu200716-Jun-11 20:37 
GeneralNice Article Pin
Jithu Jose26-Nov-10 5:53
Jithu 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.