【问题标题】:how to set id to Html.TextBox item on MVC如何在 MVC 上将 id 设置为 Html.TextBox 项
【发布时间】:2013-06-06 18:16:20
【问题描述】:

我试图通过 javascript 捕获文本框元素,以便将文本放入其中。 那么如何给文本框设置 id 呢??

        <tr>
                    // Id to this textbox
            <td>@Html.TextBoxFor(item => item.OperationNo)</td>
        </tr>

然后通过JS将文本放入其中

                            // 
   document.getElementById("Textbox id").Text= " Some text " ;

【问题讨论】:

    标签: javascript asp.net-mvc razor textbox html.textbox


    【解决方案1】:

    您可以像这样设置文本框的 ID。

    @Html.TextBoxFor(item => item.OperationNo, new { id = "MyId" })
    

    @Html.TextBoxFor(item => item.OperationNo, htmlAttributes: new { id = "MyId" })
    

    输出:

    <input ... id="MyId" name="OperationNo" type="text" />
    

    【讨论】:

    • 这将覆盖与属性名称匹配的默认 ID。
    【解决方案2】:

    您可以使用以下代码来解决该问题:

    function steVal() {
            document.getElementById('txtPlace').value = "Set The Text";
        }
    
     @Html.TextBoxFor(m => m.OperationNo,new { @id = "txtPlace",@name="txtPlace" })
    

    【讨论】:

    • 匿名类中的属性名称前不需要“@”符号。唯一需要这样做的时候是属性名称恰好是保留字,例如“class”。
    • 我竖起大拇指,因为它展示了如何做多个属性,这正是我所寻找的。 :o)
    【解决方案3】:

    应该是属性名,即OperationNo

    所以你的 JS 会是

    document.getElementById("OperationNo").html = " Some text " ;
    

    您可以使用 Chrome 或 JS 中的网络检查器查看页面上的 html 以查看元素属性。

    【讨论】:

      【解决方案4】:

      这发生在 Web 表单中使用具有相同属性的相同输入字段的场景中。就像单个视图/页面中的登录和注册表单的情况一样。 以前是这样的

      输入一个>

      <div class="field-wrap">
        @Html.TextBoxFor(model => model.Username, new { @class = "form-control",placeholder = "Username", @required = "required", autofocus = "" })
          @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
      </div> 
      

      输入二>

      <div class="field-wrap">
        @Html.TextBoxFor(model => model.Username, new { @class = "form-control", placeholder = "Username", @required = "required", autofocus = "" })
        @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
      </div>
      

      然后我为用户名输入添加了一个唯一的 id #

      新的输入一个>

      <div class="field-wrap">
        @Html.TextBoxFor(model => model.Username, new { @class = "form-control", id = "loginUsername", placeholder = "Username", @required = "required", autofocus = "" })
        @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
      </div>
      

      新的输入二>

      <div class="field-wrap">
        @Html.TextBoxFor(model => model.Username, new { @class = "form-control", id = "SignupUsername" , placeholder = "Username", @required = "required", autofocus = "" })
        @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
      </div> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-01
        • 2012-12-25
        • 2013-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多