原文发布时间为:2011-09-07 —— 来源于本人的百度文章 [由搬家工具导入]

http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-_2D00_-ASP.Net-MVC-2.0-Beta_2D00_1.aspx

Attachment(s): ExtendedEditorFor.zip

Adding html attributes support for Templates - ASP.Net MVC 2.0 Beta

ASP.Net mvc 2.0 beta, supports templates feature.  Templates are a way to write reusable view code.  They significantly simplifies the code we need to write in views.

You can read more about templates here

In this post I will show a way to extend the ModelMetadata and add support for Html Attributes which can be used in templates.

Let us assume there is a view model for "Employee"

1:publicclass Employee 2: { 3:publicstring Title { get; set; } 4:publicstring FirstName { get; set; } 5:publicstring LastName { get; set; } 6: }

 Here is the controller’s action to render the view model

1:publicclass HomeController : Controller 2: { 3:public ActionResult Index() 4: { 5: Employee employee = new Employee(); 6:return View(employee); 7: } 8: }

And the view code

<% using(Html.BeginForm())%><p><%=Html.EditorFor(e => e.Title)%></p><p><%=Html.EditorFor(e => e.FirstName)%></p><p><%=Html.EditorFor(e => e.LastName)%></p><%%>

Html for the Title field will be rendered as the following

<inputtype="text"value=""name="Title"id="Title"/>

What if we want to limit text box size of the title property and amount of data user can enter in to the textbox? 

Default metadata for the view model won’t allow us to specify these attributes.  Or the EditorFor signature won’t allow us pass in any additional html attributes. 

Instead of EditorFor, we could use TextBoxFor in the simple scenarios.  EditorFor enables the use of templates and it would be nice to have similar support for Html attributes.

One way to solve this is by decorating the view model with our own custom attributes as shown in the following snippet.

publicclass Employee{ [HtmlProperties(Size = 5, MaxLength = 10)]publicstring Title { get; set; }publicstring FirstName { get; set; }publicstring LastName { get; set; }}

Here we decorated the Title property with a custom attribute called “HtmlProperties”.  This attribute has a Size property and MaxLength property.

Code for HtmlPropertiesAttribute is straight forward.

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,AllowMultiple=false,Inherited=true)]publicclass HtmlPropertiesAttribute : Attribute {publicstring CssClass { get; set; }publicint MaxLength { get; set; }publicint Size { get; set; }public IDictionary<string,object> HtmlAttributes() {//Todo: we could use TypeDescriptor to get the dictionary of properties and their values IDictionary<string, object> htmlatts = new Dictionary<string, object>();if (MaxLength != 0) { htmlatts.Add("MaxLength", MaxLength); }if (Size != 0) { htmlatts.Add("Size", Size); }return htmlatts; } }

There is an utility method HtmlAttributes that spits out the dictionary of html attributes for use of use later.

 

Next we need to make the metdata provider aware of our new attribute.  MetadaProvides reads the metadata from the properties of view model and makes it available to the templates.

Out of the box implementation for ModelMetaDataProvider is DataAnnotationsModelMetadataProvider.  This provider has overridable method CreateMetadata.

From mvc 2.0 beta, modelmetadata supports a dictionary called AdditionalValues, which we can use as a backing store for our new metadata “HtmlAttributes”

Following is the code for our new metadataprovider

 

publicclass MetadataProvider : DataAnnotationsModelMetadataProvider {protectedoverride ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,Func<object> modelAccessor,Type modelType,string propertyName) { var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); var additionalValues = attributes.OfType<HtmlPropertiesAttribute>().FirstOrDefault();if(additionalValues != null) { metadata.AdditionalValues.Add("HtmlAttributes", additionalValues); }return metadata; } }

Once the metadata provider is ready, we need to make the template aware of this new property.

Out of the box, mvc provides a string template to render the string properties of the view model.  We can override the default implementation by creating a ViewUserControl called string.ascx  under “Views\Shared\EditorTemplates” folder of mvc project.  EditorTemplates is a new folder we need create to customize the out of box templates.

string.ascx code is shown bellow.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %><% var htmlAttributes = new HtmlPropertiesAttribute();if(ViewData.ModelMetadata.AdditionalValues.ContainsKey("HtmlAttributes")) htmlAttributes = (HtmlPropertiesAttribute) ViewData.ModelMetadata.AdditionalValues["HtmlAttributes"]; htmlAttributes.HtmlAttributes().Add("class", "text-box single-line " + htmlAttributes.CssClass); %> <span> <%= Html.Label(ViewData.ModelMetadata.PropertyName) %> <%=Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,htmlAttributes.HtmlAttributes()) %> </span>

Here we simply retrieve the HtmlAttributes dictionary from the additional values and calls its “HtmlAttributes” method and pass them to TextBox helper method.

We need to one more code change in order to tie every thing together.  In the Global.asax file, application_start method, we need to add code to replace the current ModelMetadataProvider with our implementation of metadataprovider.

protectedvoid Application_Start() { AreaRegistration.RegisterAllAreas();  RegisterRoutes(RouteTable.Routes);  ModelMetadataProviders.Current = new MetadataProvider(); }

 Rendered html code for the title after our modifications is as follows

<inputtype="text"value=""name="Title"id="Title"size="5"maxlength="10"/>

I provided the final solution as an attachment to this post

Extend Html.EditorFor MVC的更多相关文章

  1. OWIN support for the Web API 2 and MVC 5 integrations in Autofac

    Currently, in the both the Web API and MVC frameworks, dependency injection support does not come in ...

  2. 新的表格展示利器 Bootstrap Table

     1.bootstrap table简介及特征 Bootstrap Table是国人开发的一款基于 Bootstrap 的 jQuery 表格插件,通过简单的设置,就可以拥有强大的单选.多选.排序.分 ...

  3. 新的表格展示利器 Bootstrap Table Ⅰ

     1.bootstrap table简介及特征 Bootstrap Table是国人开发的一款基于 Bootstrap 的 jQuery 表格插件,通过简单的设置,就可以拥有强大的单选.多选.排序.分 ...

  4. 在Asp.Net MVC中PartialView与EditorFor和DisplayFor的区别

    相同之处: PartialView, EditorFor 和 DisplayFor 都可以用作来实现页面的公共部分,其他页面可以根据需求来引用. 不同之处: PartialView 是从Page的角度 ...

  5. mvc中EditorFor TextBoxFor什么区别

    EditorFor 是映射到Model 属性上面,忽略用户自定义属性和样式 Model 可以为nullTextBoxFor是映射到Model 属性上面,可以用户自定义属性和样式 Model 不可以为n ...

  6. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(9)-MVC与EasyUI结合增删改查

    系列目录 文章于2016-12-17日重写 在第八讲中,我们已经做到了怎么样分页.这一讲主要讲增删改查.第六讲的代码已经给出,里面包含了增删改,大家可以下载下来看下. 这讲主要是,制作漂亮的工具栏,虽 ...

  7. ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view)

    在本节中,您将验证电影控制器生成的编辑方法(Edit action methods)和视图.但是首先将修改点代码,使得发布日期属性(ReleaseDate)看上去更好.打开Models \ Movie ...

  8. 学习ASP.NET MVC(六)——我的第一个ASP.NET MVC 编辑页面

    在上一文章中由Entity Framework(实体框架)去实现了对数据库的CURD操作.在本篇文章中,主要是调试修改自动生成的动作方法和视图,以及调试编辑功能与编辑功能的Book控制器. 首先,在V ...

  9. ASP.NET MVC 学习4、Controller中添加SearchIndex页面,实现简单的查询功能

    参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-method ...

随机推荐

  1. 呕心沥血写的python猜数字

    #猜数字 import random num_rd=random.randint(0,100) count=1 while 1<=count<=10: num_ip=input('请输入0 ...

  2. C语言数组篇(五)多级指针和二维数组指针的区别

    多级指针   以二级指针为例 二级指针的由来是 指针数组 的指针形式. int *p[10] 读取的顺序是 p[] --> 10个空间的数组 * p[] --> 这10个空间的数组里面存放 ...

  3. 裸机——I2C 2

    前面的随笔完成了I2C时序分析(不涉及仲裁) 现在可以学使用控制器的I2C了. 1.先回顾I2C的基础知识 (1)总线包括SCL + SDA. (2)通信的特点: 同步,串行,电平 所以决定了 I2C ...

  4. oracle11g导出表时空表导不出解决方案

    oracle11g用exp命令导出数据库表时,有时会发现只导出了一部分表时而且不会报错,原因是有空表没有进行导出,之前一直没有找到方法于是用最笨的方法重新建这些空表,当然在我们实际当中表的数量大时我们 ...

  5. zookeeper: web ui工具的安装

    zookeeper官方没有提供web用户界面,这使很多人在使用zookeeper(动物管理员)同时,并不是很容易的理解zookeeper的数据结构,还好淘宝有位大神用Nodejs写了一个web的ui工 ...

  6. Android 第三方库RxLifecycle使用

    1.简单介绍RxLifecycle 1.1.使用原因. 在使用rxjava的时候,如果没有及时解除订阅,在退出activity的时候,异步线程还在执行. 对activity还存在引用,此时就会产生内存 ...

  7. 课后题2.87&2.86

    课后题2.86&2.87 单纯就是想加点分第十章的题目都被做过了就做下第二章的,正好复习一下前面学的知识,第二章给我剩下的题目也不多了,我就挑了这个题目. 2.86 考虑一个基于IEEE浮点格 ...

  8. P1133 教主的花园

    P1133 教主的花园 题目描述 教主有着一个环形的花园,他想在花园周围均匀地种上n棵树,但是教主花园的土壤很特别,每个位置适合种的树都不一样,一些树可能会因为不适合这个位置的土壤而损失观赏价值. 教 ...

  9. Java继承的缺点

    转载自:https://www.cnblogs.com/xz816111/archive/2018/05/24/9080173.html JAVA中使用到继承就会有两个无法回避的缺点: 1.打破了封装 ...

  10. CodeIgniter学习笔记三:扩展CI的控制器、模型

    一.扩展CI中的控制器 有时需要对CI中的控制器作统一操作,如进行登录和权限验证,这时就可以通过扩展CI控制器来实现. 扩展CI控制器只需要在application/core文件夹中建一个继承自CI_ ...