2008-08-11 19 views
6

使用的HtmlHelper渲染使用ASP.NET MVC 代碼preview 4像:你如何獲得自定義ID在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

回答

5

試試這個:

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

對於您可以將屬性的名稱前使用下劃線的任何關鍵字。你可以使用_class來代替class。由於class是C#中的關鍵字,也是HTML中的屬性名稱。現在,「id」不是C#中的關鍵字,但也許是用另一種.NET語言來支持。從我可以告訴的是,它不是VB.NET,F#或Ruby中的關鍵字,所以也許他們強迫你使用下劃線是一個錯誤。

+0

這是在文檔中描述的地方嗎? – 2010-02-20 19:11:11

0

顯然,這是一個錯誤。因爲他們將它添加到潛在的渲染值,他們只是忘了包含它。我建議在codeplex上創建一個bug,然後下載源代碼並根據需要進行修改。