Can I change the html name generated by Html.DropDownListFor?

前端 未结 9 1608
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 03:04

IDI am using the following code to create a drop down list:

 @for (var index = 0; index < Model.AdminSummaries.Count(); index++) 
            { 
            &         


        
9条回答
  •  [愿得一人]
    2021-02-05 03:31

    My solution to this issue is to replace the id and name after DropDownListFor() with a html helper extension method.

            public static MvcHtmlString ReplaceIdAndName(this MvcHtmlString htmlSource, string name)
        {
            MvcHtmlString result;
            if (name == null)
                result = htmlSource;
            else
            {
                string id = name.Replace("[", "_").Replace("]", "_").Replace(".", "_");  // HTML ids cannot have []. so MVC convention replaces with _
                XDocument html = XDocument.Parse(htmlSource.ToHtmlString());
                html.Elements().Select(e => e.Attribute("id")).FirstOrDefault().SetValue(id);
                html.Elements().Select(e => e.Attribute("name")).FirstOrDefault().SetValue(name);
                result = MvcHtmlString.Create(html.ToString());
            }
            return result;
        }
    
    
    DropDownListFor(...).ReplaceIdAndName("myclass[1].myprop");
    

提交回复
热议问题