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

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

问题描述

如您所知,我们可以在 razor 视图中为 actionLink 或 textBox 设置属性,但是我们如何将属性设置为 @Html.EditorFor,我知道 EditorFor 是一个动态元素,可以根据模型类型,但所有形状都可以获得属性.那么有没有办法将属性设置为 @Html.EditorFor 像这样: new {@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 帮助器呈现相应的编辑器模板.它可能是 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).

据说有不同的技术.例如,我非常喜欢编写一个自定义数据注释模型元数据提供程序和自定义编辑器模板,如 关注博文.

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.

另一种可能性是自定义默认模板(如 Brad Wilson 的博客文章中所示)并将不同的 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" })

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

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