设置类属性Html.EditorFor在ASP.NET MVC的Razor视图 [英] Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View

查看:394
本文介绍了设置类属性Html.EditorFor在ASP.NET MVC的Razor视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如你所知,我们可以在剃刀视图中设置属性,ActionLink的或文本框,但我们怎样才能设置属性 @ Html.EditorFor ,我知道EditorFor是一个动态元素可以根据模型类型来设置,但是,所有的形状可以得到的属性。那么,有没有办法设置属性 @ Html.EditorFor 是这样的:新{@class =MyClass的}

As you know we can set attributes to actionLink or textBox in razor views but how can we set attributes to @Html.EditorFor, I know the EditorFor is a dynamic element that can be set according to model type, but all shapes of that can get the attributes. So is there any way to set attribute to @Html.EditorFor something like this: new {@class = "myclass"} ?

推荐答案

EditorFor 帮手呈现相应的编辑器模板。它可能是<一个href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html\">default模板或者你写了一些自定义模板。这个模板可以包含任何标记。它可能包含许多DOM元素。所以,现在你明白,要求申请一类为模板没有任何意义。为了这件你想这个模板应用于这个类?例如与TextBoxFor帮手,你知道,这将产生一个输入框,是很有意义谈论应用CSS类到它(这正是在 htmlAttributes 参数允许你这样做)。

The EditorFor helper renders the corresponding editor template. It could be the default template or some custom template that you wrote. This template could contain any markup. It could contain many DOM elements. So now you understand that asking for applying a class to a template doesn't make any sense. To which element on this template you want this class to be applied? For example with the TextBoxFor helper you know that it will generate a single input field, so it makes sense to talk about applying a CSS class to it (that's exactly what the htmlAttributes argument allows you to do).

这是说有不同的技术。例如一个我很喜欢的是在<一个概述编写自定义数据模型的注解提供元数据和自定义编辑模板href=\"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\">following博客文章。

This being said there are different techniques. For example one that I like very much is to write a custom data annotations model metadata provider and custom editor templates as outlined in the following blog post.

另一种可能性是自定义默认模板(如布拉德·威尔逊的博客文章中所示),并应用不同的HTML属性对应的输入字段。让我们与string.cshtml编辑模板的例子:

Another possibility is to customize the default templates (as shown in the Brad Wilson's blog post) and apply different HTML attributes to the corresponding input field. Let's take an example with the string.cshtml editor template:

@model string
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData)

现在,当你要渲染某些字符串属性这个编辑器模板您的视图模型:

And now when you want to render this editor template for some string property on your view model:

@Html.EditorFor(x => x.SomeStringProperty, new { @class = "myclass" })

这篇关于设置类属性Html.EditorFor在ASP.NET MVC的Razor视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆