Asp.net mvc 2 in action 笔记- 4 自动代码生成、校验Validation

简介: 自动代码生成 T4 (Text Template Transformation Toolkit) is a little-known feature of Visual Studio. It’s a code-generation toolkit, and its templates allow ...

自动代码生成

T4 (Text Template Transformation Toolkit) is a little-known feature of Visual Studio. It’s a code-generation toolkit, and its templates allow us to customize how files are generated using a familiar syntax.

T4MVC

Out of the box, ASP.NET MVC contains many opportunities to get tripped up with magic strings, especially with URL generation. Magic strings are string constants that are used to represent other constructs, but with an added disconnect that can lead to subtle errors that only show up at runtime. To provide some intelligence around referencing controllers, views, and actions, the T4MVC project helps by generating a hierarchical code model representation for use inside controllers and views.

http://mvccontrib.codeplex.com/wikipage?title=T4MVC

■ T4MVC.tt

■ T4MVC.settings.t4

Html.ActionLink("Log On", "LogOn", "Account")

Html.ActionLink("Log On", MVC.Account.LogOn()

Html.ActionLink("Profile", MVC.Admin.Profile.Show(Html.Encode(Page.User.Identity.Name))

自定义T4模板

www.visualt4.com/downloads.html Visual T4 Editor 可以编辑和建立T4模板

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\CodeTemplates\AddController

         添加控制器时

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\CodeTemplates\AddView

         添加视图时使用,可以在视图中自动基于Model生成必要的代码,减少手工输入,提高效率

下的tt文件都是基于t4进行生成的

校验Validation

服务端

System.ComponentModel.DataAnnotations 下预定义了很多的验证类

如下例

public class CompanyInput

{

    [Required]

    public string CompanyName { get; set; }

 

    [DataType(DataType.EmailAddress)]

    public string EmailAddress { get; set; }

}

控制器处理程序检查ModelState.IsValid确定有效性,如下例

  [HttpPost]
        public ActionResult Edit(CompanyInput input)
        {
            if (ModelState.IsValid)
            {
                return View("Success");
            }
            return View(new CompanyInput());
        }

客户端

Microsft AJAX的方式:

  • 首先包含:
    <script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
  • 在需要验证的页面包括:
<% Html.EnableClientValidation(); %>

<h2>Client Validation</h2>

<% Html.EnableClientValidation(); %>                               

<% using (Html.BeginForm("Edit", "Home")) { %>                     

    <%= Html.EditorForModel() %>

    <button type="submit">Submit</button>

<% } %>

The EnableClientValidation method merely turns on a flag in ViewContext. It’s the BeginForm form helper method that emits the pertinent client-side scripts to enable validation. The EnableClientValidation needs to be placed before the BeginForm method in your view to correctly enable scripts.

 In our original screen with company name and email address, the model metadata is emitted as a set of JSON objects. This JSON, shown in figure 15.5, includes the model metadata information, validation information, and model information in the form of a well-structured JSON object. The generated validation information combines with the MVC validation library to act as a bridge between the client-side validation framework and the server-side model metadata emitted as JSON. For example, we can see in figure 15.5 that there seems to be some information about the CompanyName field, as well as a validation message for the required field validation.

大意是Viewer的Helper函数,根据Model的元数据信息生成客户端的验证信息

这个方式有效的把客户端、服务端的验证统一了起来

上例,察看客户端的页面代码可以看到生成的javascript代码

<script type="text/javascript">

//<![CDATA[

if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }

window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"CompanyName","ReplaceValidationMessageContents":true,"ValidationMessageId":"CompanyName_validationMessage","ValidationRules":[{"ErrorMessage":"Company Name 字段是必需的。","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"EmailAddress","ReplaceValidationMessageContents":true,"ValidationMessageId":"EmailAddress_validationMessage","ValidationRules":[]}],"FormId":"form0","ReplaceValidationSummary":false});

//]]>

</script>

相关文章
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
42 0
|
1月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
100 5
|
8月前
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
117 0
|
9月前
|
开发框架 前端开发 .NET
[回馈]ASP.NET Core MVC开发实战之商城系统(三)
[回馈]ASP.NET Core MVC开发实战之商城系统(三)
67 0
|
4月前
|
存储 SQL 开发框架
国产化之路 Linux Mono下的asp.net 开发笔记(三)
国产化之路 Linux Mono下的asp.net 开发笔记(三)
|
4月前
|
存储 SQL 开发框架
国产化之路 Linux Mono下的asp.net 开发笔记(二)
国产化之路 Linux Mono下的asp.net 开发笔记(二)
|
4月前
|
存储 开发框架 .NET
国产化之路 Linux Mono下的asp.net 开发笔记(一)
国产化之路 Linux Mono下的asp.net 开发笔记(一)
|
5月前
|
开发框架 自然语言处理 前端开发
基于ASP.NET MVC开发的、开源的个人博客系统
基于ASP.NET MVC开发的、开源的个人博客系统
52 0
|
6月前
|
开发框架 .NET 数据库
ASP.NET Core 个人博客项目搭建笔记
简易个人博客项目搭建笔记 1.概述 项目梗概通过做一个比较简单,通俗易懂的个人博客项目,很简单的增删改查,来更好学习asp.net core,这个项目使用asp.net core webapi+elementui来做。 2.数据库设计文章表ID文章标题文章内容创建时间文章类型ID浏览量点赞量作者ID文章类型表ID类型名作者表ID姓名账号密码 MD5 3.架构设计仓储层服务层 MD5加密pu...
50 1
|
8月前
|
SQL 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(完:内附源码)
经过一段时间的准备,【ASP.NET Core MVC开发实战之商城系统】已经完成,目前代码已开发完成,先将全部内容整理分享,如有不足之处,还请指正。
107 0