asp.net-mvc 如何在维护从 ViewData 检索值的同时为 Html.TextBox 助手指定属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/291274/
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-07 22:52:13  来源:igfitidea点击:

How do I specify attributes for a Html.TextBox helper while maintaining the value retrieval from ViewData?

asp.net-mvc

提问by BigJoe714

I am using the Html.TextBox helper to create textboxes. I want to set attributes on the textbox, which I understand is done using the following overload:

我正在使用 Html.TextBox 助手来创建文本框。我想在文本框上设置属性,据我所知是使用以下重载完成的:

Html.TextBox (string name, object value, object htmlAttributes)

Html.TextBox (string name, object value, object htmlAttributes)

However, I want to maintain the functionality where the HTML helper automatically uses the value from either ViewData or ViewData.Model and I do not see a way to just specify the name and the htmlAttributes. Is this possible?

但是,我想维护 HTML 帮助程序自动使用 ViewData 或 ViewData.Model 中的值的功能,并且我看不到仅指定名称和 htmlAttributes 的方法。这可能吗?

回答by tvanfosson

[EDIT] After looking at the source code, it appears that all you need to do is specify the value as null in the signature that takes a name, value, and htmlAttributes. If the value is null, it will attempt to use the value from the ViewData.

[编辑] 查看源代码后,似乎您需要做的就是在采用名称、值和 htmlAttributes 的签名中将值指定为 null。如果值为 null,它将尝试使用 ViewData 中的值。

Html.TextBox( "name", null, new { @class = "css-class" } );

回答by VnDevil

try this for razor

试试这个做剃须刀

@Html.TextBox("name", "", new {@class = "css-class", @onclick = "alert('demo');"});

回答by Andrew Van Slaars

If you don't need to supply the value from your model, you could always just use the standard HTML:

如果您不需要从模型中提供值,您可以始终使用标准 HTML:

<input type="text" name="fieldName" id="fieldName"/>

Then you can supply whatever attributes you need in the tag.

然后您可以在标签中提供您需要的任何属性。

回答by Jon Crowell

@Tvanfosson, thanks for the answer. It helped me a bunch today. I was trying to create a table with a row for every part in a list. I wanted to set several attributes based on each part, and you pointed me in the right direction. In case anybody wants to see the loop and how to set multiple attributes, here goes:

@Tvanfosson,感谢您的回答。今天它帮了我很多。我试图为列表中的每个部分创建一个表格。我想根据每个部分设置几个属性,您为我指明了正确的方向。如果有人想查看循环以及如何设置多个属性,请执行以下操作:

    <% foreach (var poPart in Model.myPartsList)
       { %>
         <tr>
             <td>
                <% var part = Model.PartID; %>
                <%: Html.TextBox(part.ToString(), null, new { @class = "narrowText", @id = part.ToString() })%>
             </td>
         </tr>
   <% } %>

回答by Newred

 @Html.TextBox("Name", "Value", new {@class = "class1 class2", @customAttributeName = "attributeValue"})