locked
Populating DropDownList with Array [MVC] RRS feed

  • Question

  • Hello.

    I'm creating a ASP.NET MVC App and I've got a small problem creating DropDownList with Week Days.

    In database I got field "DayOfWeek" which is Integer, so randomly Scaffolded Item created code for View:

            <div class="form-group">
                @Html.LabelFor(model => model.DayOfWeek, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DayOfWeek, new { htmlAttributes = new { @class = "form-control" } })          
                    @Html.ValidationMessageFor(model => model.DayOfWeek, "", new { @class = "text-danger" })
                </div>
            </div>
    

    And I'm able to select ints there. However, I want to create DropDownList in which name of days would be stored so user can pick one day and store it's INT value in the database.

    So far I created an array in model

            public string[] weekDays = new string[7] { "Monday", "Tuesday", "Wednesday", .... };
            [DisplayName("Day of week")]
            public string[] WeekDays
            {
                get { return weekDays; }
            }

    Now I'm wondering what should I put inside the View and Controller to make it work as I would like it to.

    • Moved by Caillen Friday, January 30, 2015 9:08 AM
    Tuesday, January 27, 2015 8:45 AM

Answers

All replies

  • var weekDays = new string[3] { "Monday", "Tuesday", "Wednesday"};



                var items = weekDays.Select((day, index) =>
                {
                    return new SelectListItem
                    {
                        Value = day,
                        Text = index.ToString()
                    };
                }).ToList();
                ViewBag.list = new SelectList(items, "Text", "Value");

    and in your model:

     @Html.DropDownListFor(model => model.DayOfWeek, (SelectList)ViewBag.list)

                           
    Tuesday, January 27, 2015 10:13 AM
  • MVC issues should be addressed at the ASP.NET MVC forum section.

    http://forums.asp.net/

    • Proposed as answer by Caillen Friday, January 30, 2015 9:08 AM
    • Marked as answer by Just Karl Wednesday, April 15, 2015 8:42 PM
    Tuesday, January 27, 2015 2:20 PM