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:
- Select the "Views" and create a new folder UserComment, and then right click and add a view, as shown below:
- Add the following code in the UserComment.aspx view:
<%@ 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>
- Select the "Controllers" folder and then right click and click on Controller as shown below:
- Add the following code in the UserComment.cs controller:
[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)
{
}
return View();
}
}
- 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.