将css和id选择器添加到输入框(razor helper)

时间:2015-03-28 15:47:11

标签: c# .net asp.net-mvc

在razor视图中我有razor helper呈现的文本框

@Html.EditorFor(model => model.Caption, 
       new { htmlAttributes = new { @class = "form-control" } })

我想将css id类与此表单控件类一起添加,所以我尝试了

@Html.EditorFor(model => model.Caption, 
        new { htmlAttributes = new { @class = "form-control", @id="myId" } })

但这不起作用。

2 个答案:

答案 0 :(得分:0)

如果要指定htmlAttributes,则必须使用TextBoxFor()

@Html.TextBoxFor(model => model.Caption, 
    new { @class = "form-control" } )

查看this SO post(Dimitro's Answer)

答案 1 :(得分:0)

默认您有id Caption

如果您想更改它,根据this answer,您必须从EditorFor更改为TextBoxFor。为此,我们需要删除new { htmlAttributes,因为TextBoxFor期望htmlAttributesEditorFor期望获得additionViewData

@Html.TextBoxFor(model => model.Caption, new { @class = "form-control", @id="myId" } )

我想提一下,当我测试时,您的代码会更改id

@Html.EditorFor(model => model.Caption, 
    new { htmlAttributes = new { @class = "form-control", @id="myId" } })