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>

相关文章
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
331 7
|
开发框架 .NET 数据库连接
闲话 Asp.Net Core 数据校验(三)EF Core 集成 FluentValidation 校验数据例子
闲话 Asp.Net Core 数据校验(三)EF Core 集成 FluentValidation 校验数据例子
275 1
|
开发框架 前端开发 JavaScript
基于Admin.NET框架的前端的一些改进和代码生成处理(2)
基于Admin.NET框架的前端的一些改进和代码生成处理(2)
|
开发框架 前端开发 JavaScript
基于Admin.NET框架的前端的一些改进和代码生成处理(1)
基于Admin.NET框架的前端的一些改进和代码生成处理(1)
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
337 0
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
289 0
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?
461 0
|
开发框架 .NET
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
672 0
|
JSON 前端开发 JavaScript
革新Admin.NET框架:前端体验飞跃与代码生成自动化的双重革命,引领高效开发新时代!
【8月更文挑战第3天】Admin.NET是一款专为现代企业应用打造的高效框架,凭借强大的后台管理和灵活的扩展性深受开发者喜爱。本文探讨如何优化其前端体验与开发效率。首先,通过采用Flexbox和CSS Grid等技术实现响应式布局重构,确保了不同设备上的一致体验。其次,引入Vue.js或React实现组件化开发,提高代码复用性和维护性。再者,利用Webpack等工具进行性能优化,提升页面加载速度。此外,开发了代码生成器以自动生成CRUD模块,极大提高了开发效率。这些改进使Admin.NET前端开发更高效、灵活且易于维护。
649 0
|
监控 前端开发 API
一款基于 .NET MVC 框架开发、功能全面的MES系统
一款基于 .NET MVC 框架开发、功能全面的MES系统
570 5