user2206329
user2206329

Reputation: 2842

Can someone please explain the following code

Can someone please explain the following the below code, especially the new[]

  @Html.DropDownListFor(x => x.WillAttend,new[] { 
          new SelectListItem() { Text = "Yes, I'll be there", Value = bool.TrueString},
          new SelectListItem() { Text = "No, I can't come", Value = bool.FalseString}}, "Choose an option")

Does the new[] creates a new select list?

Upvotes: 1

Views: 150

Answers (5)

RossBille
RossBille

Reputation: 1489

@Html.DropDownListFor() looks like a Razor statement for the Razor view engine. This statement will generate a HTML select list. The argmuent of this function (the stuff between the ()) makes up the contents of the list which in this case is generated from the statement new[]{...} that creates a new array populated with the items within the {} in this case SelectListItems.

The statement as a whole should generate something that looks like:

<select>
      <option value="" selected="selected" disabled="disabled">Choose an option</option>
      <option value="true">Yes, I'll be there</option>
      <option value="false">No, I can't come</option>
</select>

Upvotes: 0

Henk Mollema
Henk Mollema

Reputation: 46501

new[] is not an anonymous type, it's an implicitly typed array of type SelectListItem[]. The type of the array (SelectListItem) is inferred when you add items of type SelectListItem using the array initializer.

You are using this overload of DropDownListFor. Since SelectListItem[] derives from IEnumerable<SelectListItem, this works. You also could have used a List for example: new List<SelectListItem> { new SelectListItem { ... }, new SelectListItem { ... } }.

Upvotes: 1

Tigran
Tigran

Reputation: 62248

Does the new[] creates a new select list?

new[] creates a new Array object. Considering that second parameter of DropDownListFor is IEnumerable<SelectListItem>, array smoothly casts to required type.

Upvotes: 0

Complexity
Complexity

Reputation: 5820

That's correct, the new[] in an array, list initializer. So in this case, you create an array or a list, I don't know the type which a dropdownlistfor accepts and it has 2 items of type SelectListItem.

Upvotes: 0

LockTar
LockTar

Reputation: 5465

The code creates a new array of the type SelectList and adds two new SelectListItem items to it. That is your new dropdownlist.

Upvotes: 0

Related Questions