如何在MVC中使用HtmlHelper获取要呈现的自定义ID
时间:2020-03-05 18:39:01 来源:igfitidea点击:
使用ASP.NET MVC预览4
像这样的代码:
<%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>
仅输出:
<input type="checkbox" value="True" name="myCheckBox" />
回传表单中有一个"名称",而JavaScript或者标签中没有" id" :-(
我希望将其更改为:
Html.CheckBox( "myCheckBox", "Click Here", "True", false, new { id="myCheckBox" } )
会工作,但我得到一个例外:
System.ArgumentException: An item with the same key has already been added.
好像集合中某处已经有一个ID,我很困惑!
感兴趣的人的完整例外说明如下(嘿,在此处添加文件不是很好):
System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Web.Routing.RouteValueDictionary.Add(String key, Object value) at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes) at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108
解决方案
回答
显然这是一个错误。因为他们将其添加到潜在的渲染值中,所以他们只是忘记了将其包括在内。我建议在Codeplex上创建一个错误,然后下载源代码并根据需要对其进行修改。
回答
试试这个:
<%= Html.CheckBox("myCheckbox", "Click here", "True", false, new {_id ="test" })%>
对于任何关键字,可以在属性名称前使用下划线。我们可以使用_class代替class。由于class是C#中的关键字,因此也是HTML中属性的名称。现在," id"不是C#中的关键字,但也许它是他们想要支持的另一种.NET语言。据我所知,它不是VB.NET,F#或者Ruby中的关键字,因此强迫他们在其上使用下划线可能是一个错误。