开发者

ASP MVC 3: How to apply style to just some of the items of a drop down?

I have the following requirement. I have a drop down that display machine parts. The parts that have the active property set as "false" should be displayed in bold red text while the others in regular text.

The problem is that the SelectItem cl开发者_C百科ass does not have an htmlproperty to set this, only the Dropdown helper, but that is applied to the whole list, I just want this for some of the items.


I had this requirement a while ago. The good news is that a solution is straightforward. The bad news is that it involves copy/pasting a lot of code from the MVC3 source.

Please find the code pasted here, as it's really too much to paste inline.

It consists of an interface IHtmlAttributes (for an object that may carry such data), the class SelectListItemWithAttributes (you will be creating objects of this class), and a static class where you will need to paste a whole lot of extension methods.

After you do this, it's pretty straightforward:

var item = new SelectListItemWithAttributes(new { @class = "inactive" });
item.Text = "Foo";
item.Value = "Bar";

You put all these into any IEnumerable<SelectListItemWithAttributes>, call one of the DropDownList family of methods pasted into the static helper class and that's all there is to it.


You could easily achieve this with jquery:

<script type="text/javascript">
    $(document).ready(function () {        
        $('#IdOfYourDropDown option:disabled').css('color', 'red');
    });
</script>

It selects all options within the dropdown which are disabled and adds some inline styling, you could also add a css class if you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜