如何在ASP.NET MVC中设置HTML Helper文本框的宽度?

48

我找到了一些在较旧版本的mvc中显然有效的示例,这些示例表明有一种长度参数:

<%=Html.TextBox("test", 50)%>

但可能错误地设置了该值。

在当前版本中,如何使用?传递样式似乎没有任何效果。

8个回答

67

最初的答案不再像原来那样有效:

<%=Html.TextBox("test", new { style="width:50px" })%> 

这将为您获取一个文本框,其文本内容为 "{ style="width:50px" }"。

要调整此内容以适应当前的 MVC 1.0 版本,请使用以下脚本(请注意添加第二个参数 - 我的起始为空白,请根据您的需求进行相应调整):

<%=Html.TextBox("test", "", new { style="width:50px" })%> 

42
为此,您需要使用HtmlAttributes,但有一个问题:HtmlAttributes和css类

您可以这样定义:

new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };

以下是一个更加实际的例子:

new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}

最后在:

MVC 1

<%= Html.TextBox("test", new { style="width:50px" }) %> 

MVC 2

<%= Html.TextBox("test", null, new { style="width:50px" }) %> 

MVC 3

@Html.TextBox("test", null, new { style="width:50px" })

6

类似以下这样的代码应该可以正常工作:

<%=Html.TextBox("test", new { style="width:50px" })%>

或者更好的方法:
<%=Html.TextBox("test")%>

<style type="text/css">
    input[type="text"] { width:50px; }     
</style>

2

1

我的MVC 3的真实示例在这里:

<% using (Html.BeginForm()) { %>

<p>

Start Date: <%: Html.TextBox("datepicker1", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

End Date: <%: Html.TextBox("datepicker2", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

<input type="submit" name="btnSubmit" value="Search" /> 

</p>

<% } %>

所以,我们有以下内容

"datepicker1" - 控件的ID

DateTime.Now.ToString("MM/dd/yyyy") - 默认值

style = "width:80px;" - 文本框的宽度

maxlength = 10 - 我们只能输入10个字符


MVC 4 仍未发布,这是一年前发布的 抬起眉毛 - IAmGroot

1
不要使用长度参数,因为它不能在所有浏览器中正常工作。最好的方法是在输入标签上设置样式。
<input style="width:100px" />

0

新的 { style="width:50px", maxsize = 50 };

应该是

新的 { style="width:50px", maxlength = 50 };


0

在mvc3.0中设置文本框的宽度和最大长度

@Html.TextBoxFor(model => model.SearchUrl, new { style = "width:650px;",maxlength = 250 }) 

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