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
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) ...
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With