asp.net-mvc 如何在@Html.TextBox mvc4 中同时添加css class 和id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16643928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:51:22  来源:igfitidea点击:

How to add css class and id in @Html.TextBox mvc4 at the same time

asp.net-mvcasp.net-mvc-4

提问by Heidel

I need to add css class and id in @Html.TextBox mvc4 at the same time. I try

我需要同时在@Html.TextBox mvc4 中添加css class 和id。我试试

@Html.TextBox("name", new { id = "name"}, new { @class = "text-field" })

but as result I get

但结果我得到

 <input class="text-field" id="name" name="name" type="text" value="{ id = name }">

I dont need attribute value here.
I need to get

我在这里不需要属性值。
我需要得到

 <input type="text" value="" name="name" id="name" class="text-field" />

回答by AliR?za Ad?yah?i

Correct overload method

正确的重载方法

public static MvcHtmlString TextBox(
    this HtmlHelper htmlHelper,
    string name,
    Object value,
    Object htmlAttributes
)

you want to use idas HtmlAttribute, so you should use it in HtmlAttributes object. Correct usage of TextBoxis:

你想id用作 HtmlAttribute,所以你应该在 HtmlAttributes 对象中使用它。正确的用法TextBox是:

@Html.TextBox("name", 
    null,
    new { 
        id = "name", 
        @class = "text-field" 
})

if you place idin route object, then id will be a route value.

如果你放置id在路由对象中,那么 id 将是一个路由值。

回答by Gorgsenegger

Try

尝试

@Html.TextBox("name", 
    null,
    new { 
        id = "name", 
        @class = "text-field" 
    })

回答by vibs2006

I simply use the newkeyword. For example see the following code

我只是使用new关键字。例如看下面的代码

@Html.TextBoxFor(m => m.Venue, new { @class = "form-control", @id = "AnyCustomID" })