Thursday 26 April 2012

ASP.NET MVC - Set width to Dropdownlist

How to set the width for the dropdownlist in ASP.NET MVC

when using anonymous objects to pass attributes like width you only need @ if the attribute is a c# reserved word. For example, lets say you want to set the css class you would put

@Html.DropDownListFor(model => model.WidgetName, new SelectList(ViewBag.WidgetsDetail, "WidgetName", "WidgetName"), new { class="ddl })

However, because in c# the word class means define a new C# class (object) the compiler would cause an error and not allow you to compile. The way around this is to use @class, which tells the compiler "I want to name this property class".

For properties like id and style, you do not nead the @ since it's not part of the C# language definition. so this will work:
@Html.DropDownListFor(model => model.WidgetName, new SelectList(ViewBag.WidgetsDetail, "WidgetName", "WidgetName"), new {id="ddWidgets", style="width:500px"})

1 comment:

  1. doesn't work as Select element found with in ul element... which is automaticaly generated by razor.

    ReplyDelete