当我们利用Visual Studio生成实体类以后,难免会用到验证功能(例如,用户登录时验证用户名是否为空,并加以显示)。

Visual Studio实体类:实体类

如果直接去编辑Visual Studio生成的实体类话,当数据库更新字段后,再次更新实体类的话,会覆盖我们所添加的验证代码。

那么我们就要避免在Visual Studio生成的类中去进行代码的编写。这就需要用到扩展Models类了。

1、让我们创建一个AccountModels.cs文件.

生成AccountModels,cs文件

2、开始编写AccountModels.cs(模型)文件的代码,注意注释的描述,对你的学习很有帮助.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;//所添加的自定义验证引用
using System.ComponentModel;//所添加的自定义验证引用 namespace MvcTest.Models
{
/// <summary>
/// 指定元数据类
/// </summary>
[MetadataType(typeof(MemberMetadata))]
//类名与MvcTest.edmx的表名相同,partial为局部类型修饰词,用来和实体数据类进行整合
public partial class Member
{
public class MemberMetadata
{ [DisplayName("用户id")]
public int Id { get; set; } [Required]//必须字符
[DisplayName("用户名")]//定义说明文字,调用方法:<%: Html.LabelFor(m => m.UserName) %>
public string UserName { get; set; } [Required]
[StringMinLength(6, 18, ErrorMessage = "密码大于6,小于18")]//自定义验证,下面有代码
[DataType(DataType.Password)]
[DisplayName("密码")]
public string PassWord { get; set; } [Required]
[Email(ErrorMessage = "请输入正确的Email")]//自定义验证,下面有代码
[DisplayName("Email")]
public string Email { get; set; } [Required]
[DisplayName("创建时间")]
public DateTime CreateTime { get; set; } [Required]
[DisplayName("最后登录时间")]
public DateTime LogonTime { get; set; } [Required]
[DisplayName("安全问题")]
public string Quesion { get; set; } [Required]
[DisplayName("安全答案")]
public string Answer { get; set; }
}
/// <summary>
/// 定义StringMinLength类,继承ValidationAttribute验证基础类
/// </summary>
public class StringMinLength : ValidationAttribute
{
private int _MinLength;
private int _MaxLength;
/// <summary>
/// 定义方法,进行赋值
/// </summary>
/// <param name="MinLength">最小值</param>
/// <param name="MaxLength">最大值</param>
public StringMinLength(int MinLength, int MaxLength)
{
_MinLength = MinLength;
_MaxLength = MaxLength;
}
/// <summary>
/// 重写IsValid方法
/// </summary>
/// <param name="value">验证时所传入的值,不管StringMinLength()方法定义几个参数,重写时只这样写:IsValid(object value)</param>
/// <returns>override重写修饰符</returns>
public override bool IsValid(object value)
{
if (value.ToString().Length < _MinLength)
{
return false;
}
if (value.ToString().Length > _MaxLength)
{
return false;
}
return true;
}
}
/// <summary>
/// 定义EmailAttribute类,继承RegularExpressionAttribute正则表达式类,做验证使用,可重复调用
/// </summary>
public class EmailAttribute : RegularExpressionAttribute
{
// base 关键字用于从派生类中访问基类的成员
public EmailAttribute() : base(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4})$") { }
}
}
}

3、编写View(视图)代码.View我们用的是强类型绑定,还需要调用三个js,因为View用了母版页.所以另贴代码.这三个JS是验证时必须调用的.

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> </title>
<script type="text/javascript" src="../../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcValidation.js"></script>
</head>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcTest.Models.Member>" %>
<%--Inherits="System.Web.Mvc.ViewPage<MvcTest.Models.Member>" 强类型--%>
<asp:Content ID="registerTitle" ContentPlaceHolderID="TitleContent" runat="server">
注册
</asp:Content>
<asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>
创建新帐户</h2>
<p>
使用以下表单创建新帐户。
</p>
<%--启用验证方法,必须在第一个using (Html.BeginForm())上面,Html的<form>标签无效--%>
<%Html.EnableClientValidation(); %>
<%--生成form表单--%>
<% using (Html.BeginForm())
{ %>
<div>
<fieldset>
<legend>帐户信息</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName) %>
<%--验证失败时所显示的错误信息--%>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.PassWord) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.PassWord)%>
<%: Html.ValidationMessageFor(m => m.PassWord)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Email) %>
<%: Html.ValidationMessageFor(m => m.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Quesion) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Quesion)%>
<%: Html.ValidationMessageFor(m => m.Quesion)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Answer) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Answer)%>
<%: Html.ValidationMessageFor(m => m.Answer)%>
</div>
<p>
<input type="submit" value="注册" />
</p>
</fieldset>
</div>
<% } %>
</asp:Content>

4、编写Controllers(控制器)

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MvcTest.Models;//需要using Models. namespace MvcTest.Controllers
{ [HandleError]//处理由操作方法引发的异常
public class AccountController : Controller
{
//new实体类
MvcTestEntities db = new MvcTestEntities(); #region 注册
public ActionResult Register()
{
return View();
}
[HttpPost]//为了避免在表单未提交的时候访问此注册方法,需加[HttpPost],只有通过在本页面通过Post传输方式提交的表单才会访问此方法
public ActionResult Register(Models.Member member)
{
//做验证判断,如果通过则执行数据库写入代码
if (ModelState.IsValid)
{
db.AddToMember(new Models.Member
{
UserName = member.UserName,
PassWord = member.PassWord,
Email = member.Email,
Quesion = member.Quesion,
Answer = member.Answer,
CreateTime = DateTime.Now,
LogonTime = DateTime.Now
});
db.SaveChanges();
//跳转页面.参数1:操作名称,参数2:路由参数
return RedirectToAction("Index", "Home");
}
return View();
}
#endregion
}
}

运行效果

 
以上为全部代码。如有问题可留言.

MVC2 扩展Models和自定义验证(学习笔记)的更多相关文章

  1. 扩展jquery.validate自定义验证,自定义提示,本地化

    <!DOCTYPE html> <html> <head> <meta name="viewport" content="wid ...

  2. Angular.js之服务与自定义服务学习笔记

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. Angular.js之自定义指令学习笔记

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  4. sql server自定义函数学习笔记

    sql server中函数分别有:表值函数.标量函数.聚合函数.系统函数.这些函数中除系统函数外其他函数都需要用户进行自定义. 一.表值函数 简单表值函数 创建 create function fu_ ...

  5. Android自定义View学习笔记(一)

    绘制基础 参考:HenCoder Android 开发进阶: 自定义 View 1-1 绘制基础 Paint详解 参考:HenCoder Android 开发进阶: 自定义 View 1-2 Pain ...

  6. Java SpringBoot 如何使用 IdentityServer4 作为验证学习笔记

    这边记录下如何使用IdentityServer4 作为 Java SpringBoot 的 认证服务器和令牌颁发服务器.本人也是新手,所以理解不足的地方请多多指教.另外由于真的很久没有写中文了,用词不 ...

  7. 【转载】自定义View学习笔记之详解onMeasure

    网上对自定义View总结的文章都很多,但是自己还是写一篇,好记性不如多敲字! 其实自定义View就是三大流程,onMeasure.onLayout.onDraw.看名字就知道,onMeasure是用来 ...

  8. Kotlin学习笔记(9)- 数据类

    系列文章全部为本人的学习笔记,若有任何不妥之处,随时欢迎拍砖指正.如果你觉得我的文章对你有用,欢迎关注我,我们一起学习进步! Kotlin学习笔记(1)- 环境配置 Kotlin学习笔记(2)- 空安 ...

  9. python3.4学习笔记(二十五) Python 调用mysql redis实例代码

    python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...

随机推荐

  1. 云服务器 ECS Linux Ubuntu 主机修改主机名

    云服务器 ECS Linux 主机修改主机名 修改云服务器 ECS Linux 主机名常见的有两种方式,本文对此进行概要说明. 临时生效修改 使用命令行修改 hostname 主机名(可自定义),重新 ...

  2. Jquery——hover与toggle

    hover方法的语法结构为:hover(enter,leave) hover()当鼠标移动到元素上时,会触发第一个方法,当鼠标移开的时候会触发第二个方法 复制代码 <html> <h ...

  3. MySql服务初始化、安装、启动

    /// <summary> /// 安装并开启服务 /// </summary> public static bool InitAndStartService(string s ...

  4. python object对象

    动态语言的对象属性 既然都是动态语言,自然python和熟知的JavaScript很像,建一个空对象用来存放所有的数据,看看js: var data = {}; data.name = 'CooMar ...

  5. Communication API

    Stingray WIKI Stingray javascript Communication 主要的三个方法: Communication.LinkRequest - 页面跳转,调用比较简单,直接参 ...

  6. sell 项目 类目表 设计 及 创建

    1.数据库设计 2.类目表 创建 /** * 类目表 */ create table `product_category` ( `category_id` int not null auto_incr ...

  7. ReactNative踩坑日志——代码执行方式(面向对象)

    在ReactNative中,是以面向对象的方式执行代码的.处于同一{}內的代码以对象的形式执行,也就是说,程序虽然会自上而下执行代码,但是它会保证当前整个代码块內的语句执行完毕才执行下一代码块. 举个 ...

  8. 使用tar+pigz+ssh实现大数据的高效传输

    以前我们跨主机拷贝大数据的时候,比如要拷贝超过100GB的mysql原始数据,我们通常的做法如下: 在源端打包压缩为tar.gz文件 采用scp或者rsync等方式拷贝到目标主机 在目标主机解压文件 ...

  9. POJ 3268 Bookshelf 2 动态规划法题解

    Description Farmer John recently bought another bookshelf for the cow library, but the shelf is gett ...

  10. 单目视觉里程计 mono vo

    之前为了修改svo进行了一些不同的尝试,两个视频demo在以下. 效果1 视频链接: https://v.qq.com/x/page/d0383rpx3ap.html 在不同数据集上測试 效果2 视频 ...