如何对 asp.net mvc @Html.TextboxFor 应用样式?

36

我想改变文本框的背景。这是我的代码:

@Html.TextBoxFor(p => p.Publishers[0].pub_name)

在TextBoxFor中需要写入什么内容才能更改背景?

3个回答

62

TextBoxFor方法的一个重载允许您传递一个对象作为HTML属性。

@Html.TextBoxFor(p => p.Publishers[0].pub_name, new { Class="YourBackgroundClass" })

然后您可以使用以下CSS规则:

.YourBackgroundClass { background:#cccccc; }

如果您想直接应用样式,可以这样做:

@Html.TextBoxFor(p => p.Publishers[0].pub_name, new { Style="background:#cccccc;" })

谢谢。如果我不想使用类,而是直接指定一些属性怎么办?我尝试过了,但这样不起作用:@Html.TextBoxFor(p => p.Publishers[0].pub_name, new { foreground = "red" }) - TCM
同时使用你的例子是不行的。我得到了错误,因为class是保留字。 - TCM
3
@Anthony: 我修正了示例,应该是@class,因为 class 是保留关键字。 - Dan Abramov
2
“foreground”属性不起作用,因为它不是HTML属性,你必须从“webforms”的思维方式中脱离出来,这些属性是纯HTML的。如果您不想使用类,则可以使用“Style”属性使用内联样式。 - rkaregaran
@rkaregaran:谢谢,我现在已经将我的注意力从Webforms中分离出来并将其置于一旁。你的解决方案完美地解决了我的问题! - TCM
显示剩余4条评论

12

在我的情况下,我做了以下操作。我有一个ASP.NET MVC应用程序,我们正在使用Bootstrap。我为所有的div元素设置了float:left。 只是想展示如何在@Html.TextBoxFor中同时使用@style和@class

<div class="modal-body" style="height:auto; overflow-y:auto;max-height:500px;">
  <table style="width:100%" cellpadding="10">
     <tr>
       <td>
         <div style="display: inline; ">
            <label style=" float:left; margin-right:20px;">Login Name: </label>
            @Html.TextBoxFor(m => Model.UserPrincipalName, new { @id = "LoginName", @class = "form-control", @style = "float:left;margin-right:10px;margin-top:-5px;" })
            <a href="#" onclick="SearchActiveDirectoryByLoginName()" title="Search Active Directory" class="btn btn-primary" style="float: left; margin-top: -5px;">
                  @Html.Raw(" Search ")
             </a>
         </div>
       </td>
      </tr>
  </table>
</div>

在这里输入图片描述


1
现在您可以像这样添加HTML属性:

 @Html.EditorFor(p => p.Publishers[0].pub_name, new { htmlAttributes = new { @class = 
 "YourBackgroundClass" } })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接