SumitS.
SumitS.

Reputation: 65

How to pass List<string> to dropdown?

I have a list as follows:

List<string>WeekEnding={'10/07/2018','11/11/2018','01/21/2018'};

I want to pass it to the dropdown with name='10/07/2018' value='10/07/2018'

my dropdown is

  @Html.DropDownList("WeekEnding", null, new { Id = "WeekEnding", style = "width:50px;", @class = "form-control js-select", @size = "2" , required = "required" })  

Upvotes: 1

Views: 2992

Answers (2)

Brendan Vogt
Brendan Vogt

Reputation: 26018

I normally use view models to populate my drop down lists, even if it has basic values like dates (as in your code). Working on the way that you are wanting it, I would have done it like below.

Assuming you are working with the Index action method and Index view..

Index action method

public ActionResult Index()
{
    List<string> WeekEnding = new List<string>() { "10/07/2018", "11/11/2018", "01/21/2018" };

    return View(WeekEnding);
}

Index view

@model List<string>

@Html.DropDownList(
    "WeekEnding",
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    ),
    "-- Select --",
    new { @style = "width: 50px", @class = "form-control js-select", @size = "2", @required = "required" }
)

When viewing the HTML source after the page has been generated would look like this:

<select class="form-control js-select" id="WeekEnding" name="WeekEnding" required="required" size="2" style="width: 50px">
    <option value="">-- Select --</option>
    <option value="10/07/2018">10/07/2018</option>
    <option value="11/11/2018">11/11/2018</option>
    <option value="01/21/2018">01/21/2018</option>
</select>

I hope this helps.

Upvotes: 1

Eldaniz Ismayilov
Eldaniz Ismayilov

Reputation: 856

You can use like this

@model List<string>
@Html.DropDownList(
    "WeekEnding", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),//you have to pass data as model. If you use another way you must change this line. 
        "Value",
        "Text"
    ),
    new { Id = "WeekEnding", style = "width:50px;", @class = "form-control js-select", @size = "2" , required = "required" }
)

Upvotes: 1

Related Questions