如果我有一个像这样的 HTML 助手:

Name:<br />
<%=Html.TextBox("txtName",20) %><br />

如何对其应用 CSS 类?我必须把它包裹在跨度中吗?或者我是否需要以某种方式利用助手的 HtmlAttributes 属性?

有帮助吗?

解决方案

您可以将其作为参数传递到 TextBox 调用中。

Name:<br/>    
<%= Html.TextBox("txtName", "20", new { @class = "hello" }) %>

此行将创建一个值为 20 的文本框,并为 class 属性分配值 hello。我把@字符放在类前面,因为类是保留关键字。如果要添加其他属性,只需用逗号分隔键/值对即可。

其他提示

这是如何在同一元素上添加类和样式......

“x”是传递给具有 TextBoxID 属性的视图的模型

@Html.TextBoxFor(x => x.TextBoxID, new { @class = "SearchBarSelect", style = "width: 20px; background-color: green;" })

我做了一些研究,发现这篇文章似乎可以解决您的问题。

使用 ASP.NET MVC 的 Ajax 控制工具包#

来源:吉姆齐默曼

文章链接

http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330

引用

因此,基本上,如果您将类TextBoxWatermark放在任何文本框输入上,则将您喜欢以这样的水印显示为标题:

<input type="text" class"TextboxWatermark" name="username" id="username" title="Must be at least 6 chars" />

或者

<%= Html.TextBox("username", new { @class = "TextboxWatermark", @title = "Must be at least 6 chars" }) %>

第二个选项的好处是,如果在ViewData.model中有一个var命名为'username'的viewData中有一个项目,那么您获得了获取视图引擎以填写文本框的值的额外好处。

使用 htmlAttributes 具有匿名类型的参数,例如 tihs:

<%=Html.TextBox("txtName","20", new { @class = "test"}) %>

助手实现

public static class LabelExtensioncs
{
    public static MvcHtmlString Alarm(this HtmlHelper helper, string target, string text)
    {
        return MvcHtmlString.Create(string.Format("<p class='alert' style='background-color: #b8f89d;border-radius: 5px;width: 100%;'><b>{0}</b><br /><i>{1}</i></p>", target, text));
    }    
}

视图部分的用法

@Html.Alarm("Title", "please unsure your card no is invisible in your authorized information")

结果enter image description here

不需要使用跨度,因为它不是动态的。

CSS:

.testClass {
color: #1600d3;
}

查看(索引):

@Html.TextBox("expression", "Text to show.", new { @class = "testClass" })

如果您需要动态选项,您可以使用例如:

CSS:

.test class{
background: #ffffff;
}

控制器(测试索引):

[HttpGet]
public ActionResult Index()
{
ViewBag.vbColor = "#000000";
return View();
}

查看(索引):

<div>
<span>
@Html.TextBox("expression", "Text to show.", new 
{ @class = "testClass", @style="color: " + 
@ViewBag.vbColor })
</span>
</div>

希望能帮助到你。

还需要那么多工作吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top