c# - Disable an item in the Dropdownlist in my MVC3 -
i have mvc3 application. want disable particular item in dropdown list
based on condition.
@html.dropdownlist("reportname", model.reporttypes, new { style = "color:black; float:left; padding:5px;", @id = "reporttype" }) @if (model.numcount > 500) { // disable item value = "rc-report"; }
populate list of selectlistitemextends, , pass on viewbag:
viewbag.list = new biz().listsmall() .select(s => new selectlistitemextends() { text = s.dsc, value = s.id, enabled = s.is_active }).toarray();
in view use:
@html.dropdownlist("id", viewbag.list ienumerable<selectlistitemextends>, new { })
create file htmlhelperextensions.cs:
using system.collections.generic; using system.web.routing; namespace system.web.mvc.html { public static class htmlhelperextensions { public static mvchtmlstring dropdownlist(this htmlhelper htmlhelper, string name, ienumerable<selectlistitemextends> selectlist, object htmlattributes)//, func<object, bool> itemdisabled) { //creating select element using tagbuilder class create dropdown. tagbuilder dropdown = new tagbuilder("select"); //setting name , id attribute name parameter passed method. dropdown.attributes.add("name", name); dropdown.attributes.add("id", name); var options = ""; tagbuilder option; //iterated on ienumerable list. foreach (var item in selectlist) { option = new tagbuilder("option"); option.mergeattribute("value", item.value.tostring()); if (item.enabled == false) option.mergeattribute("disabled", "disabled"); if (item.propextends != null) option.mergeattributes(item.propextends); option.setinnertext(item.text); options += option.tostring(tagrendermode.normal) + "\n"; } //assigned options dropdown using innerhtml property. dropdown.innerhtml = options.tostring(); //assigning attributes passed htmlattributes object. dropdown.mergeattributes(new routevaluedictionary(htmlattributes)); //returning entire select or dropdown control in htmlstring format. return mvchtmlstring.create(dropdown.tostring(tagrendermode.normal)); } } public class selectlistitemextends : selectlistitem { public bool enabled { get; set; } public idictionary<string, string> propextends { get; set; } } }
the result is:
<select name="id" id="id"> <option value="430">object 1</option> <option value="5c7" disabled="disabled">object 2</option> </select>
att
julio spader
Comments
Post a Comment