如何在MVC中使用HtmlHelper获取自定义ID

问题描述 投票:6回答:2

使用preview 4ASP.NET MVC代码如:

<%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>

只输出:

<input type="checkbox"  value="True"  name="myCheckBox"  />

有一个name那里的形式发布回来但没有id的javascript或标签:-(

我希望将其改为:

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
asp.net-mvc html-helper
2个回答
5
投票

试试这个:

<%= Html.CheckBox("myCheckbox", "Click here", "True", false, new {_id ="test" })%>

对于任何关键字,您可以在属性名称前使用下划线。而不是类,你使用_class。由于class是C#中的关键字,因此也是HTML中属性的名称。现在,“id”不是C#中的关键字,但它可能是他们想要支持的另一种.NET语言。据我所知,它不是VB.NET,F#或Ruby中的关键字,因此可能是一个错误,它们强迫您使用下划线。


0
投票

显然这是一个错误。因为他们将它添加到潜在的渲染值,他们只是忘了包含它。我建议在codeplex上创建一个bug,然后下载源代码并根据需要进行修改。

© www.soinside.com 2019 - 2024. All rights reserved.