Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML helper DropDownList explained

Can someone please explain how this works? (which overload is being used)

@Html.DropDownList("FinancialYearID", "Select FY")

FinancialYearID is a SelectList in view bag. Why is it passed as a string?

Also how can I add custom attributes on the input element? Adding a 3rd parameter

new { @class = "foo" } 

doesn't work?

Is it possible to add data- attributes using the default helpers?

Thanks

like image 740
den Avatar asked May 29 '14 15:05

den


People also ask

What is HTML DropDownList?

Definition and Usage. The <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted) ...

What is difference between DropDownList and DropDownListFor?

DropdownListFor is support strongly type and it name assign by lambda Expression so it shows compile time error if have any error. DropdownList not support this.

What is HTML helper method?

An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.


1 Answers

You're calling this overload. This creates a dropdown list with the name "FinancialYearID" (which means that the selected value will bind to a model or ViewBag property called "FinancialYearID") and "Select FY" as the placeholder (empty) selection text.

If you want to add a class, you need the DropDown(string, IEnumerable, string, object) helper:

@Html.DropDownList("FinancialYearID", null, "Select FY", new { @class = "foo" })

Here, you can also populate the DropDownList by passing in an IEnumerable (such as a SelectList) where I have passed null.

Yes, it is entirely possible to pass a data attribute. just replace the hyphen with an underscore:

@Html.DropDownListFor("FinancialYearID", null,
                   "Select FY", new { @data_something = "foo" })

If you have a model property to which you're trying to bind the selected value, you can pass a lamba expression to indicate the property that you want to bind and the framework will generate the appropriate name:

@Html.DropDownList(m => m.FinancialYearID, MySelectList,
                   "Select FY", new { @data_something = "foo" })

I'd also generally advise putting the SelectList in the model on the initial GET request rather than using ViewBag.

like image 119
Ant P Avatar answered Oct 11 '22 14:10

Ant P