Data Validation with Entity Framework Database First in ASP.NET MVC


Create a database named LearnASPNETMVCWithRealApps. This database have a table: Account table as below:

USE LearnASPNETMVCWithRealApps

/* Table structure for table `account` */

GO
CREATE TABLE Account (
    Username varchar(50) NOT NULL PRIMARY KEY,
	Password varchar(50) NULL,
	FullName nvarchar(50) NULL,
	Age int NULL,
	Email varchar(50) NULL,
	Website varchar(50) NULL
)

On the Visual Studio, create new ASP.NET MVC Web Application project

Select Empty Template and Core Reference is MVC




In Models folder, use the Entity Wizard to create Entity Data Model from Database in Visual Studio. This file use Entity Framework interact with the database.

In Models folder, create new meta data classes as below:

Create new class named AccountMetaData.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace LearnASPNETMVCWithRealApps.Models
{
    public class AccountMetaData
    {
        [MinLength(3)]
        [MaxLength(10)]
        [Required]
        [Display(Name = "Username")]
        public string Username
        {
            get;
            set;
        }

        [Required]
        [RegularExpression("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})")]
        [Display(Name = "Password")]
        public string Password
        {
            get;
            set;
        }

        [Required]
        [Display(Name = "Full Name")]
        public string FullName
        {
            get;
            set;
        }

        [Range(18, 120)]
        [Required]
        [Display(Name = "Age")]
        public int Age
        {
            get;
            set;
        }

        [EmailAddress]
        [Required]
        [Display(Name = "Email")]
        public string Email
        {
            get;
            set;
        }

        [Url]
        [Display(Name = "Website")]
        public string Website
        {
            get;
            set;
        }

    }

    [MetadataType(typeof(AccountMetaData))]
    public partial class Account
    {
    }

}

In Controllers folder, create new controller named AccountController.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LearnASPNETMVCWithRealApps.Models;

namespace LearnASPNETMVCWithRealApps.Controllers
{
    public class AccountController : Controller
    {
        private LearnASPNETMVCWithRealAppsEntities db = new LearnASPNETMVCWithRealAppsEntities();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Save(Account account)
        {
            if (ModelState.IsValid)
            {
                return View("Success");
            }
            else
            {
                return View("Index");
            }
        }

    }
}




In Views/Account folder, create new razor views as below:

Create new view named Index.cshtml as below:

@{
    Layout = null;
}

@model LearnASPNETMVCWithRealApps.Models.Account

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Account Register</h3>
    @using (Html.BeginForm("Save", "Account"))
    {
        <table cellpadding="2" cellspacing="2" border="0">
            <tr>
                <td>Username</td>
                <td>@Html.TextBoxFor(model => model.Username)</td>
                <td>@Html.ValidationMessageFor(model => model.Username)</td>
            </tr>
            <tr>
                <td>Password</td>
                <td>@Html.PasswordFor(model => model.Password)</td>
                <td>@Html.ValidationMessageFor(model => model.Password)</td>
            </tr>
            <tr>
                <td>Full Name</td>
                <td>@Html.TextBoxFor(model => model.FullName)</td>
                <td>@Html.ValidationMessageFor(model => model.FullName)</td>
            </tr>
            <tr>
                <td>Age</td>
                <td>@Html.TextBoxFor(model => model.Age)</td>
                <td>@Html.ValidationMessageFor(model => model.Age)</td>
            </tr>
            <tr>
                <td>Email</td>
                <td>@Html.TextBoxFor(model => model.Email)</td>
                <td>@Html.ValidationMessageFor(model => model.Email)</td>
            </tr>
            <tr>
                <td>Website</td>
                <td>@Html.TextBoxFor(model => model.Website)</td>
                <td>@Html.ValidationMessageFor(model => model.Website)</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="2"><input type="submit" value="Save" /></td>
            </tr>
        </table>
    }

</body>
</html>

Create new razor view named Success.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Success</title>
</head>
<body>

    <h3>Account Info</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <td>Username</td>
            <td>@ViewBag.account.Username</td>
        </tr>
        <tr>
            <td>Password</td>
            <td>@ViewBag.account.Password</td>
        </tr>
        <tr>
            <td>Full Name</td>
            <td>@ViewBag.account.FullName</td>
        </tr>
        <tr>
            <td>Age</td>
            <td>@ViewBag.account.Age</td>
        </tr>
        <tr>
            <td>Email</td>
            <td>@ViewBag.account.Email</td>
        </tr>
        <tr>
            <td>Website</td>
            <td>@ViewBag.account.Website</td>
        </tr>
    </table>
</body>
</html>




Access Index action in Account controller with following url: http://localhost:9596/Account/Index

Output

Click Save button submit form to Save action in Account controller with some instances of invalid data as below:

Case 1

Case 2

Click Save button submit form to Save action in Account controller with valid data

Output

I recommend you refer to the books below to learn more about the knowledge in this article: