【问题标题】:Change text box size in the view更改视图中的文本框大小
【发布时间】:2014-04-07 08:44:38
【问题描述】:

我创建了 MVC5 应用程序,它通过脚手架视图和控制器从我的模型生成 目前文本框的默认大小是 18 个字符,我希望它是 5、如何减小文本框的默认大小?

<div class="form-group">
    @Html.LabelFor(model => model.num, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Nun)
        @Html.ValidationMessageFor(model => model.Num)
    </div>
</div>

我试过没有成功

  @Html.EditorFor(model => model.Nun, new { @style = "width: 100px;" })

【问题讨论】:

  • 按大小,你是指框的实际宽度,还是可以输入的字符数?
  • @wf4 是框的宽度...
  • css 类 col-md-10 是否决定了文本框的大小?

标签: html asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor


【解决方案1】:

你做不到的原因

@Html.EditorFor(model => model.Nun, new { style = "width: 100px;" }) 

是因为EditorFor 可能包含多个对象。因此,在设置 ID 和样式的情况下,您会将属性应用于可能不正确的内容。

因此,您可以通过多种方式来设置框的样式。

此 CSS 将为您完成:(您可以只使用 1 行或所有适用的行)

.col-md-10 input                 { width:50px }     /* <input> */    
.col-md-10 input[type=text]      { width:50px }     /* <input type="text"> */
.col-md-10 input[type=password]  { width:50px }     /* <input type="password"> */
.col-md-10 textarea              { width:50px }     /* <textarea> */

例如,作为.col-md-10 的子元素的任何&lt;input type="text"&gt; 都将设置为50px 宽。

或者您可以改用TextBoxFor,这将允许您添加内联样式:

@Html.TextBoxFor(model => model.Nun, new { style = "width: 50px;" })

【讨论】:

    【解决方案2】:

    使用TextBoxFor

    @Html.TextBoxFor(model => model.Nun, new { @style = "width: 100px;" })
    

    检查此LINK 。如果您不想使用TextBoxFor 而不是EditorFor

    【讨论】:

      【解决方案3】:

      在模型中对 Nun 属性执行以下操作:

      [StringLength(6)]
      public string Nun {get;set;}
      

      如果你想改变宽度,那么:

      @Html.TextBoxFor(model => model.Nun,new {style="width:100px" })
      

      【讨论】:

      • 谢谢,但这是限制您可以在文本框中输入的字符数,而不是它的大小...
      • 您不想将用户限制为 6 个字符?
      • 然后查看更新版本的答案,希望对您有所帮助