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

Tagged as

Go to top

MVC Application - Part 1 - Validation

, 26 Jun 2010
Rate this:
Please Sign up or sign in to vote.
An application to demonstrate MVC validation

Introduction - Part 1 - Validation

This is a several part article to show how MVC can be used to write an application. Part 1 shows the usage of creating an EntityFramework database, a controller, a view and some validation. Over the course of a few articles, we will write an application showing multiple areas of what MVC can do and various features in MVC.

Background

I started to do this since MVC was new and wanted to learn it since I know this will be a great technology. All you should need to know is some C# and as I get into some of the technology, other MVC articles will help. I will not get into what is a controller and a view at this time since there are plenty of articles that do a great job on describing that.

Creating the Application

The first thing to do is create a MVC application. Once you start Visual Studio, create a sample MVC 2 application. After VS2010 creates the sample application, you can run the skeleton, and it should look like this:

SampleAppdb/Blank Screen

Now let's create a database that holds an Employee table. This table will show and edit the data. This script can be run in the SQL management console to create it.

if exists (select * from dbo.sysobjects where name = 'Employee' and type = 'U')
	drop table Employee
GO

CREATE TABLE Employee (
	Emp_Id           int IDENTITY(1,1) PRIMARY KEY NOT NULL,
	Emp_FirstName    varchar (50) NOT NULL,
	Emp_MiddleName   varchar (50) NOT NULL,
	Emp_LastName     varchar (50) NOT NULL,
	Emp_Gender       varchar (50) NOT NULL,
	Emp_BirthMonth   int NOT NULL,
	Emp_BirthDay     int NOT NULL,
	Emp_City         varchar (50) NOT NULL,
	Emp_State        varchar (50) NOT NULL,
)
GO

To use the database, we need to create the entities. From the project, select add new and Add new Entity Data Model.

create model

Since we created the database in SQL management, we need to create the entities from the database we previously created.

create model

Since I never started the database, I need to create a database connection. Let's create one now:

create model

This is our new connection, and before we proceed, let's test the connection.

create model

To create the entities, we need to select a table.

create model

I will skip the creation of the controller since they are not unique to this article, the only thing I will say is to create the action methods. I also created the controller named as EmployeeController, since it tells you it is the Employee table. When making the views, I created an Index (List), a Details, Create and an Edit view. Next, I added a link to the employee view in the sitemaster page so we can now view our new code.

<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<li><%: Html.ActionLink("Employee", "Index", "Employee")%></li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>

Now add the code to the controllers for accessing the database. You can look at the included code to see the examples. Make sure that you only display the needed data in the index view since it will be longer than can be displayed. The details view can show the entire record. If you need to see it, you can scroll. If you have done this so far you have an application that can create, edit, and view an employee table. But we allow bad data, so let's fix that. We will add some metadata to the start of each property for the Employee data to define what is required, and its format. Since C# allows partial classes, we could just add the metanames to the EDM file but the next time we generate the class, we lose the edits. We need to create a buddy class, so we do not lose our edits.

Normally we would add a metatag such as [Required] before the property name, but we will put these in the buddy file which will then be associated with the main properties. I have added a few metanames to the properties for our testing as shown below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
using System.Resources;
using Social2.Properties;

namespace Social2.Models
{
    [MetadataType(typeof(Employee_Metadata))]
    public partial class Employee
    {
        public partial class Employee_Metadata
        {
            [DisplayName("Employee Idd")]
            public global::System.Int32 Emp_Id { get; set; }

            [DisplayName("Employee First Name")]
            public global::System.String Emp_FirstName { get; set; }

            [DisplayName("Employee Middle Name")]
            [StringLength(10, ErrorMessage="Name Must be under 10 Characters")]
            [Required]
            public global::System.String Emp_MiddleName { get; set; }

            [DisplayName("Employee LastName")]
            [StringLength(10, ErrorMessageResourceType = 
		typeof(Resource), ErrorMessageResourceName = "StrLastNameength")]
            public global::System.String Emp_LastName { get; set; }

            [DisplayName("Employee Gender")]
            public global::System.String Emp_Gender { get; set; }

            [DisplayName("Employee Birth Month")]
            public global::System.Int32 Emp_BirthMonth  { get; set; }

            [DisplayName("Employee Birth Day")]
            public global::System.Int32 Emp_BirthDay  { get; set; }

            [DisplayName("Employee City")]
            public global::System.String Emp_City  { get; set; }

            [DisplayName("Employee State")]
            public global::System.String Emp_State { get; set; }
        }
    }
}

Now you can see that most of the metanames are the displayname which will change the name you use in a label field. But you also see the fields for Required and Stringlength. To just change the display names, those are all the code changes that need to be done. Now that we have real display names, let's make sure the input is valid. You can add code to the server and the client to do the same things we will be doing but this method allows us to add the code once and it applies to both the client and the sever.

The metanames will tell the system what to check for. For the first pass, let's enable just the server side checking since it has to be done anyways. When an error happens, let's make sure the validation is displayed on the client, in the view make sure the code has the "validationsummary" before the beginform and has any text you want to display.

<h2>Edit</h2>
<%= Html.ValidationSummary("Edit was unsuccessful. 
	Please correct the errors and try again.")%>
<% using (Html.BeginForm()) {%>

In the controller, we need to catch the error and redisplay the edit so the user can change the data that does not meet the requirements. Add the following code to see if there is an error in the model and return.

public ActionResult Edit(Employee Emp_Ins_toEdit)
{
    if (ModelState.IsValid == false)
    {
        return View(Emp_Ins_toEdit);
    }

What the two of these will do is tell the system what to check and set the modelstate to an invalid state. Then we check the state and return the same data for the view. The result will be a display with an error message of what to change.

Error display

This is a great start to allow you to use labels and validation. Now let's add one more item and use a resource file so we can display different text based on whatever we need such as a different language. So the first piece we need to add a resource file. In the "Add New" dialog, select the resource file.

resouce display

As you probably noted, I added the line in the metanames buddy class to access the resource file and did not mention it. I am sure all of you thought this is an error but it was since I did not mention we would be adding a resource file. All of the metanames that all text can reference the resource file, so when a stringlength metaname is executed and the error message is needed, it will reference the resource file. We also have to make sure the resource name is entered into the resource file.

[DisplayName("Employee LastName")]
[StringLength(10, ErrorMessageResourceType = 
	typeof(Resource), ErrorMessageResourceName = "StrLastNameength")]
public global::System.String Emp_LastName { get; set; }

One real advantage about the resource file is that all of the messages and labels are centrally located, so you can alter them in whatever way you need.

resouce entry

Now to enable client side validation, edit the sitemaster file as follows. We need to call a function EnableClientValidation to do this and add some JavaScript to have it work on the client.

<asp:ContentPlaceHolder ID="sonScripts" runat="server" >
    <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" 
	type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" 
	type="text/javascript">

This is all that is needed to be done to enable validation on the client side. We now have both client and server side validation using resource files as well.

Points of Interest

I learned a lot from finding and reading all of the various articles that put this together. I did learn how to do validation using metadata and using resource files in an MVC application. I hope this helps someone since it took a lot of reading to get me to this point. There are very good articles describing in much more detail than I did, so if you want to learn more, please read the other articles.

History

  • 28 June 2010 - Initial release

License

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

Share

About the Author

Donsw
Web Developer
United States United States
I am a Director of Engineering, have an MBA and work in C# forms, Asp.Net and vb.net. I have been writing Windows program since windows 3.0. I am currently working in the Healthcare industry.
 
I enjoy reading, music (most types), cars, and cigars. I am involved in opensource projects at codeplex.
 
My linkedin link is
http://www.linkedin.com/in/donsweitzer
Follow on   Twitter   Google+

Comments and Discussions

 
General[My vote of 2] Subject not covered PinmvpMark Nischalke6-Jul-10 2:44 
GeneralMy vote of 2 Pinmembertongleea26-Jun-10 15:20 

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
Web04 | 2.8.140916.1 | Last Updated 26 Jun 2010
Article Copyright 2010 by Donsw
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid