Radio Button generates duplicate HTML id-s

前端 未结 3 1818
闹比i
闹比i 2020-12-30 19:41

It seems that the default ASP.NET MVC2 Html helper generates duplicate HTML IDs when using code like this (EditorTemplates/UserType.ascx):

&         


        
3条回答
  •  粉色の甜心
    2020-12-30 20:15

    I faced the same problem. Specyfying IDs manually seems to be the only solution. If you don't need the ids for anything (like javascript), but want it only to be unique you could generate Guids for them:

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

    A more elegant solution would be to create your own extension method on HtmlHelper to separate ID creation logic from the view. Something like:

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

    The helper method could use ViewContext and Model data to create more meaningfull IDs.

    UPDATE:

    If you use EditorTemplates to render the control like this

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

    Then inside the MyUserControl.ascx (placed in ~/Views/Shared/EditorTemplates) you can use ViewData.TemplateInfo.HtmlFieldPrefix property to access the parent control ID or Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("MyPostfixPart") to generate prefixed id. Theese methods could be used in the helper extension above. The same works with controls rendered with Html.Editor(...) and Html.EditorForModel(...). In the Html.Editor helper you can also specify htmlFiledName manually if you want.

    When you embed the control with

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

    generation of meaningfull IDs is harder because the Html.Partial will not provide information about the prefix - the ViewData.TemplateInfo.HtmlFieldPrefix will be always empty. Then, the only solution would be to pass the prefix manually to the ascx control in as ViewData key of as a model field which is not as elegant a solution as the previous one.

提交回复
热议问题