2010-05-10 30 views
32

似乎默认ASP.NET MVC2 HTML辅助生成重复的HTML标识使用这样的代码(EditorTemplates/UserType.ascx)时:单选按钮生成HTML重复ID-S

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UserType>" %> 

<%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary) %> 
<%: Html.RadioButton("", UserType.Standard, Model == UserType.Standard) %> 
<%: Html.RadioButton("", UserType.ReadOnly, Model == UserType.ReadOnly) %> 

的HTML它产生的是:

<input checked="checked" id="UserType" name="UserType" type="radio" value="Primary" /> 
<input id="UserType" name="UserType" type="radio" value="Standard" /> 
<input id="UserType" name="UserType" type="radio" value="ReadOnly" /> 

这就清楚地表明了一个问题。所以我必须滥用帮手或其他东西。

我可以手动指定id作为html属性,但我不能保证它是唯一的。

所以,问题是如何确保通过单选助手生成的ID是唯一的每个值和仍然保留约定产生这些ID(所以嵌套模型得到尊重?(最好不要手动生成的ID )

回答

12

我面临同样的问题手工识别ID似乎是唯一的解决方案如果你不需要任何东西(如JavaScript)的ID,但只希望它是唯一的,你可以为他们生成GUID :

<%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary, new { id="radio" + Guid.NewGuid().ToString()}) %> 

更优雅的解决方案是在HtmlHelper上创建您自己的扩展方法,以便从视图中分离ID创建逻辑。例如:

public static class HtmlHelperExtensions 
{ 

    public static MvcHtmlString MyRadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool value) 
    { 
     string myId = // generate id... 
     return htmlHelper.RadioButtonFor(expression, value, new {id=myId}); 
    } 
} 

帮助器方法可以使用ViewContext和Model数据来创建更多有意义的ID。

UPDATE:

如果使用EditorTemplates呈现这样

<%= Html.EditorFor(m=>m.User, "MyUserControl") %> 

然后MyUserControl.ascx内部的控制(置于〜/查看/共享/ EditorTemplates),可以使用ViewData.TemplateInfo.HtmlFieldPrefix属性访问父控制ID或Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("MyPostfixPart")以生成前缀ID。 Theese方法可以用在上面的助手扩展中。 与使用Html.Editor(...)Html.EditorForModel(...)呈现的控件相同。在Html.Editor帮助程序中,如果需要,也可以手动指定htmlFiledName。

当您嵌入与

<%= Html.Partial("UserControl", Model.User) %> 

代meaningfull ID的更难,因为Html.Partial不会提供有关前缀信息的控制 - 在ViewData.TemplateInfo.HtmlFieldPrefix将永远是空的。然后,唯一的解决方案就是手动将前缀作为模型字段的ViewData键传递给ascx控件,这与前一个解决方案不太一样。

+0

也许你也可以建议如何生成的ID考虑到模型的账户当前名称,以便ID可以正确生成和有这样的ID:'UserType_Primary','Company_User_UserType_Primary'等等? – 2010-05-11 23:47:37

+0

@Dmitriy:我刚刚更新了我的回复。 ViewData.TemplateInfo.HtmlFieldPrefix应该可以帮到你。 – PanJanek 2010-05-12 10:57:01

+0

非常感谢。这应该为我做这份工作。 – 2010-05-12 23:38:55

14

除了PanJanek的回答是:
如果你并不真正需要的元素有一个id,你还可以指定在htmlAttributes id=""佣工(即new { id="" })参数。这将导致id属性在生成的html中完全省略。

来源:https://stackoverflow.com/a/2398670/210336

0

如果确实需要通过jQuery访问单选按钮,我发现,往往是更好的地方设置id的将是页,接近其预期的使用上。这是我做了同样的:

@Html.Label(Resource.Question) 
@Html.RadioButtonFor(m => m.Question, true, new {id = "QuestionYes"}) Yes 
@Html.RadioButtonFor(m => m.Question, false, new {id = "QuestionNo"}) No 

然后我的jQuery:

if ($("input[id='QuestionNo']").is(":checked")) { 
     $('#YesOptionalBlock').removeClass('showDiv'); 
     $('#YesOptionalBlock').addClass('hideDiv'); 
}