将css类添加到Html中。EditorFor MVC 2

时间:2022-09-26 20:58:34

I'm trying to add a css class to a textbox. This is what I have in my view:

我想在文本框中添加一个css类。这就是我的观点:

<%: Html.EditorFor(m => m.StartDate) %>

I tried following the instructions at this link by making my code:

我试着按照这个链接上的说明做我的代码:

<%: Html.EditorFor(m => m.StartDate, new { @class: "datepicker" }) %>

But I get a compiler error saying:

但是我得到一个编译错误说:

Syntax error, ',' expected

语法错误,”、“预期

What am I doing wrong here?

我在这里做错了什么?

8 个解决方案

#1


25  

I would HIGHLY suggest using Editor Templates. It's definitely the "right" way to style your EditorFor.

我强烈建议使用编辑器模板。这绝对是你编辑风格的“正确”方式。

You can tell a model property to use an Editor Template in two different ways.

您可以告诉模型属性以两种不同的方式使用编辑器模板。

The first (the simplest) is to create an editor template for a certain data type - DateTime for example.
The second way to do it is to set it declaratively in your DataAnnotations by using a UIHint.

第一个(最简单的)是为特定数据类型创建编辑器模板——例如DateTime。第二种方法是使用UIHint在dataannotation中以声明的方式设置它。

Edit
I'd also like to add that you should use the "date" type in your input field so that even when JavaScript is disabled, your user can stills see a native datepicker (only valid on modern HTML5 browsers)
<input id="meeting" type="date" value="2011-01-13"/>

我还想补充一点,您应该在输入字段中使用“date”类型,这样即使禁用了JavaScript,您的用户仍然可以看到一个本地datepicker(仅在现代HTML5浏览器上有效)

#2


78  

With MVC3, I kept banging my head because I couldn't get this to work. I didn't want to create a whole EditorTemplate for just adding one class.

有了MVC3,我一直在敲我的头,因为我不能让它工作。我不想为添加一个类创建一个完整的编辑器模板。

Well, instead of using EditorFor, use TextBoxFor, with of course the equals sign like so:

不是使用EditorFor,而是TextBoxFor,当然等号是这样的

@Html.TextBoxFor(m=> m.ZipCode, new { @class = "zip" })

#3


5  

I guess a quick and dirty way to do this would be in jQuery, yes?

我猜一种快速而肮脏的方法是jQuery,对吧?

$(document).ready(function () {
    $('#StartDate').addClass('datepicker');
});

#4


4  

Ideally, you should use the Editor Templates. I got around this issue by using the Editor Template inside the MvcHtmlString.Create() which will let you rebuild the actual HTML code. Of course, you'll want to copy everything in the "class" section to keep the Editor Template as useful as possible.

理想情况下,您应该使用编辑器模板。我通过在MvcHtmlString.Create()中使用编辑器模板来解决这个问题,该模板将允许您重新构建实际的HTML代码。当然,您将希望复制“class”部分中的所有内容,以使编辑器模板尽可能有用。

I tried many of the suggestions above, but eventually, I settled on this, because I think it's less complicated and it lets me continue using Editor Templates:

我尝试了上面的许多建议,但最终我决定了,因为我认为它不那么复杂,它让我可以继续使用编辑器模板:

@MvcHtmlString.Create(Html.EditorFor(m => m.StartDate).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line datepicker\""))

#5


3  

There is no overload for EditorFor that allows you to set HtmlProperties. (IDictionary htmlAttributes)

对于编辑器来说,没有重载允许您设置HtmlProperties。(IDictionary htmlAttributes)

This link explains how to do it:

这个链接解释了怎么做:

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

http://aspadvice.com/blogs/kiran/archive/2009/11/29/adding - html -属性-支持-模板- 2 d00 beta_2d00_1.aspx——asp.net mvc - 2.0

#6


3  

I know this is an old question but thought I could contribute so here goes. I had the same problem and wanted to avoid making Editor Templates. I just wanted a generic handle everything solution that would allow me to specify html attributes when using Html.EditorFor in a view.

我知道这是一个老问题,但我认为我可以做出贡献。我也有同样的问题,希望避免制作编辑器模板。我只是想要一个通用句柄everything解决方案,允许我在使用html时指定html属性。EditorFor视图。

I really liked CIAs answer, but I expanded on it a bit so that you can pass in any attributes you need. I created an extra Html.EditorFor method that accepts html attributes:-

我非常喜欢CIAs的回答,但我对它做了一些扩展,以便您可以传入任何需要的属性。我创建了一个额外的Html。接受html属性的编辑器:-

public static class EditorForExtentions
{
    public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes, bool extendAttributes)
    {
        string value = html.EditorFor(expression).ToString();

        PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
        foreach (PropertyInfo info in properties)
        {
            int index = value.ToLower().IndexOf(info.Name.ToLower() + "=");
            if (index < 0)
                value = value.Insert(value.Length - (value.EndsWith("/>") ? 2 : 1), info.Name.ToLower() + "=\"" + info.GetValue(htmlAttributes, null) + "\"");
            else if (extendAttributes)
                value = value.Insert(index + info.Name.Length + 2, info.GetValue(htmlAttributes, null) + " ");            
        }

        return MvcHtmlString.Create(value);
    }
}

You can call it in a view like this

你可以这样调用它

<%=Html.EditorFor(m => m.StartDate, new { @class = "datepicker" }, true)%>

It uses the normal Html.EditorFor method to get the html string, then injects the html attributes needed.

它使用普通的Html。获取html字符串的EditorFor方法,然后注入所需的html属性。

#7


1  

I was looking for a solution to apply a style to a specific box generated by the @HTML.EditorFor helper method.

我正在寻找一个解决方案,将样式应用到由@HTML生成的特定框中。EditorFor helper方法。

The question was regarding setting a CSS class for @HTML.EditorFor but for anyone who wants to edit the style for a single element.. you can, for example, try this:

问题是关于为@HTML设置CSS类。但是对于任何想要为单个元素编辑样式的人。例如,你可以试试这个:

In my block, I added a style based on the ID generated by the helper: ..

在我的block中,我添加了一个基于助手生成的ID的样式:..

<style> 
    #EnrollmentInfo_Format
    {
        width:50px;
        font: normal 100% 'Lucida Grande',Tahoma,sans-serif;
        font-size: 11px;
        color: #2e6e9e;
    }
</style>

and then in my page (i'm doing this in a partial view):

然后在我的页面(我在部分视图中做这个):

@Html.EditorFor(e => e.EnrollmentInfo.Format)

#8


-3  

Here's a very simple solution: Remove the double quotes from "datepicker" and retype them back into Visual Studio and it should work.

这里有一个非常简单的解决方案:删除“datepicker”中的双引号,并将它们重新输入到Visual Studio中,这样就可以工作了。

I had the same problem. I copied/pasted sample code from the web and the code had a special type of quote which caused the "," syntax problem. I know it's really not obvious.

我也有同样的问题。我从web上复制/粘贴示例代码,代码有一种特殊类型的引号,这导致了“,”语法问题。我知道这并不明显。

#1


25  

I would HIGHLY suggest using Editor Templates. It's definitely the "right" way to style your EditorFor.

我强烈建议使用编辑器模板。这绝对是你编辑风格的“正确”方式。

You can tell a model property to use an Editor Template in two different ways.

您可以告诉模型属性以两种不同的方式使用编辑器模板。

The first (the simplest) is to create an editor template for a certain data type - DateTime for example.
The second way to do it is to set it declaratively in your DataAnnotations by using a UIHint.

第一个(最简单的)是为特定数据类型创建编辑器模板——例如DateTime。第二种方法是使用UIHint在dataannotation中以声明的方式设置它。

Edit
I'd also like to add that you should use the "date" type in your input field so that even when JavaScript is disabled, your user can stills see a native datepicker (only valid on modern HTML5 browsers)
<input id="meeting" type="date" value="2011-01-13"/>

我还想补充一点,您应该在输入字段中使用“date”类型,这样即使禁用了JavaScript,您的用户仍然可以看到一个本地datepicker(仅在现代HTML5浏览器上有效)

#2


78  

With MVC3, I kept banging my head because I couldn't get this to work. I didn't want to create a whole EditorTemplate for just adding one class.

有了MVC3,我一直在敲我的头,因为我不能让它工作。我不想为添加一个类创建一个完整的编辑器模板。

Well, instead of using EditorFor, use TextBoxFor, with of course the equals sign like so:

不是使用EditorFor,而是TextBoxFor,当然等号是这样的

@Html.TextBoxFor(m=> m.ZipCode, new { @class = "zip" })

#3


5  

I guess a quick and dirty way to do this would be in jQuery, yes?

我猜一种快速而肮脏的方法是jQuery,对吧?

$(document).ready(function () {
    $('#StartDate').addClass('datepicker');
});

#4


4  

Ideally, you should use the Editor Templates. I got around this issue by using the Editor Template inside the MvcHtmlString.Create() which will let you rebuild the actual HTML code. Of course, you'll want to copy everything in the "class" section to keep the Editor Template as useful as possible.

理想情况下,您应该使用编辑器模板。我通过在MvcHtmlString.Create()中使用编辑器模板来解决这个问题,该模板将允许您重新构建实际的HTML代码。当然,您将希望复制“class”部分中的所有内容,以使编辑器模板尽可能有用。

I tried many of the suggestions above, but eventually, I settled on this, because I think it's less complicated and it lets me continue using Editor Templates:

我尝试了上面的许多建议,但最终我决定了,因为我认为它不那么复杂,它让我可以继续使用编辑器模板:

@MvcHtmlString.Create(Html.EditorFor(m => m.StartDate).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line datepicker\""))

#5


3  

There is no overload for EditorFor that allows you to set HtmlProperties. (IDictionary htmlAttributes)

对于编辑器来说,没有重载允许您设置HtmlProperties。(IDictionary htmlAttributes)

This link explains how to do it:

这个链接解释了怎么做:

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

http://aspadvice.com/blogs/kiran/archive/2009/11/29/adding - html -属性-支持-模板- 2 d00 beta_2d00_1.aspx——asp.net mvc - 2.0

#6


3  

I know this is an old question but thought I could contribute so here goes. I had the same problem and wanted to avoid making Editor Templates. I just wanted a generic handle everything solution that would allow me to specify html attributes when using Html.EditorFor in a view.

我知道这是一个老问题,但我认为我可以做出贡献。我也有同样的问题,希望避免制作编辑器模板。我只是想要一个通用句柄everything解决方案,允许我在使用html时指定html属性。EditorFor视图。

I really liked CIAs answer, but I expanded on it a bit so that you can pass in any attributes you need. I created an extra Html.EditorFor method that accepts html attributes:-

我非常喜欢CIAs的回答,但我对它做了一些扩展,以便您可以传入任何需要的属性。我创建了一个额外的Html。接受html属性的编辑器:-

public static class EditorForExtentions
{
    public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes, bool extendAttributes)
    {
        string value = html.EditorFor(expression).ToString();

        PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
        foreach (PropertyInfo info in properties)
        {
            int index = value.ToLower().IndexOf(info.Name.ToLower() + "=");
            if (index < 0)
                value = value.Insert(value.Length - (value.EndsWith("/>") ? 2 : 1), info.Name.ToLower() + "=\"" + info.GetValue(htmlAttributes, null) + "\"");
            else if (extendAttributes)
                value = value.Insert(index + info.Name.Length + 2, info.GetValue(htmlAttributes, null) + " ");            
        }

        return MvcHtmlString.Create(value);
    }
}

You can call it in a view like this

你可以这样调用它

<%=Html.EditorFor(m => m.StartDate, new { @class = "datepicker" }, true)%>

It uses the normal Html.EditorFor method to get the html string, then injects the html attributes needed.

它使用普通的Html。获取html字符串的EditorFor方法,然后注入所需的html属性。

#7


1  

I was looking for a solution to apply a style to a specific box generated by the @HTML.EditorFor helper method.

我正在寻找一个解决方案,将样式应用到由@HTML生成的特定框中。EditorFor helper方法。

The question was regarding setting a CSS class for @HTML.EditorFor but for anyone who wants to edit the style for a single element.. you can, for example, try this:

问题是关于为@HTML设置CSS类。但是对于任何想要为单个元素编辑样式的人。例如,你可以试试这个:

In my block, I added a style based on the ID generated by the helper: ..

在我的block中,我添加了一个基于助手生成的ID的样式:..

<style> 
    #EnrollmentInfo_Format
    {
        width:50px;
        font: normal 100% 'Lucida Grande',Tahoma,sans-serif;
        font-size: 11px;
        color: #2e6e9e;
    }
</style>

and then in my page (i'm doing this in a partial view):

然后在我的页面(我在部分视图中做这个):

@Html.EditorFor(e => e.EnrollmentInfo.Format)

#8


-3  

Here's a very simple solution: Remove the double quotes from "datepicker" and retype them back into Visual Studio and it should work.

这里有一个非常简单的解决方案:删除“datepicker”中的双引号,并将它们重新输入到Visual Studio中,这样就可以工作了。

I had the same problem. I copied/pasted sample code from the web and the code had a special type of quote which caused the "," syntax problem. I know it's really not obvious.

我也有同样的问题。我从web上复制/粘贴示例代码,代码有一种特殊类型的引号,这导致了“,”语法问题。我知道这并不明显。