MVC has DropDownList method, very useful, but the most commonly used needs, a group of CheckBoxList how do not have a similar method? Depressed, do yourself a bar, directly on the code
Public StaticMvchtmlstring CheckBoxList ( ThisHtmlHelper Helper,stringName, ienumerable<selectlistitem>selectlist) { returnCheckBoxList (helper, name, SelectList,New { }); } Public StaticMvchtmlstring CheckBoxList ( ThisHtmlHelper Helper,stringName, Ienumerable<selectlistitem> SelectList,Objecthtmlattributes) {IDictionary<string,Object> htmlattributes =htmlhelper.anonymousobjecttohtmlattributes (htmlattributes); HashSet<string>Set=Newhashset<string>(); List<SelectListItem> list =NewList<selectlistitem>(); stringSelectedvalues = convert.tostring ((selectlist asselectlist). SelectedValue); if(!string. IsNullOrEmpty (selectedvalues)) {if(Selectedvalues.contains (",")) { string[] TempStr = Selectedvalues.split (','); for(inti =0; i < tempstr.length; i++) { Set. ADD (Tempstr[i]); } } Else { Set. ADD (selectedvalues); } } foreach(SelectListItem Iteminchselectlist) {Item. Selected= (item. Value! =NULL) ?Set. Contains (item. Value):Set. Contains (item. Text); list. ADD (item); } selectlist=list; Htmlattributes.add ("type","checkbox"); Htmlattributes.add ("ID", name); Htmlattributes.add ("name", name); Htmlattributes.add ("style","margin:0 0 0 10px;line-height:30px; Vertical-align:-8px;border:none;"); StringBuilder StringBuilder=NewStringBuilder ();foreach(SelectListItem SelectIteminchselectlist) {IDictionary<string,Object> newhtmlattributes =htmlattributes.deepcopy (); Newhtmlattributes.add ("value", Selectitem.value); if(selectitem.selected) {Newhtmlattributes.add ("checked","checked"); } tagbuilder Tagbuilder=NewTagbuilder ("input"); Tagbuilder.mergeattributes<string,Object>(newhtmlattributes);stringInputallhtml=tagbuilder.tostring (tagrendermode.selfclosing); Stringbuilder.appendformat (@"<label style= "" margin:0 0 0 10px; "" > {0} {1}</label>", inputallhtml, Selectitem.text); } returnmvchtmlstring.create (stringbuilder.tostring ());} Private Staticidictionary<string,Object> Deepcopy ( Thisidictionary<string,Object>HT) {Dictionary<string,Object> _ht=Newdictionary<string,Object>(); foreach(varPinchHT) {_ht. ADD (P.key, P.value); } return_ht;}
You can take it directly.
Each checkbox generated has a label outside it, feels good, does not like to be removed, and has a htmlattributes.add ("style", "margin:0 0 0 10px;line-height:30px; Vertical-align:-8px;border:none; "); To make the display look better, if it's not in your style, you can get rid of it.
A HtmlHelper method is extended in. NET MVC3 CheckBoxList