locked
displaying the selected item on dropdownlist when editing my form RRS feed

  • Question

  • User202943253 posted

    Hi,

    I have a dropdown  listsupplied statically.

    <div class="form-group">
       <div class="form-row">
            @Html.LabelFor(model => model.TYPE, htmlAttributes: new { @class = "control-label col-md-4" })
             <div class="col-md-8">
                 @Html.DropDownListFor(model => model.TYPE, new SelectList(
                     new List<Object>{
                     new { value = "" , text = ""  },
                     new { value = "1" , text = "Type 1"  },
                     new { value = "2" , text = "Type 2" },
                    },
                   "value",
                   "text",
                    0), new { @class = "form-control" })
                                                </div>
                                            </div>
                                        </div>


    when adding, it sends the value 1 or 2 and saved it correctly in my database.

    during the modification, I would like to select the right value that I retrieved from the database knowing that I retrieved correctly the good element to modify and its other text values and also the value of of my dropdown list .

    How can i represent my dropdownlist by displaying the selected item when editing my form? 

    Thanks !

    Thursday, January 14, 2021 2:52 PM

All replies

  • User475983607 posted

    This requirement is covered in any beginning level MVC tutorial.  Rather than hard coding the SelectList in the View, populate the SelectList in the Action and pass the object to the View.

    Google

    https://www.google.com/search?q=mvc+select+dropdown+value+from+model

    First item in the list.

    https://stackoverflow.com/questions/27901175/how-to-get-dropdownlist-selectedvalue-in-controller-in-mvc

    Other Blogs/Tutorials/Forum.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

    https://forums.asp.net/t/2116783.aspx?Model+Binding+and+SelectList

    Thursday, January 14, 2021 3:07 PM
  • User1429838465 posted

    I also agree your SelectList should be generated on the server and the result passed into the ViewModel.

    I have an extension method to assist in building SelectLists which also handles default values in your SelectList.

    public static class ListExtensions
    {
        public static IEnumerable<SelectListItem> ToSelectList<T>(
            this IEnumerable<T> list, Func<T, string> dataField,
            Func<T, string> valueField, string defaultValue)
        {
            var result = new List<SelectListItem>();
            if (list.Any())
                result.AddRange(
                    list.Select(
                        resultItem => new SelectListItem
                        {
                            Value = valueField(resultItem),
                            Text = dataField(resultItem),
                            Selected = defaultValue == valueField(resultItem)
                        }));
            return result;
        }
    }

    Usage:

    viewModel.UserSelectList = list.ToSelectList(e => e.Name, e => e.UserId, "2");

    Hope this helps.

    Reference:

    Thursday, January 14, 2021 3:26 PM
  • User-1545767719 posted

    silbahi

    during the modification, I would like to select the right value that I retrieved from the database knowing that I retrieved correctly the good element to modify and its other text values and also the value of of my dropdown list .

    How can i represent my dropdownlist by displaying the selected item when editing my form? 

    Try below:

    Controller / Action Method

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Mvc5App2.Controllers
    {
        public class HomeController : Controller
        {
            // existing action methods ... omitted
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                List<Item> list = new List<Item> { 
                    new Item { Text = "Type 1", Value="1" },
                    new Item { Text = "Type 2", Value="2" }
                };
    
                // to be retrieved from the database
                // Tentatively set to “2” to see the DropDownList selects “2”
                string selectedValue = "2"; 
    
                ViewBag.Items = new SelectList(list, "Value", "Text", selectedValue);
    
                return View();
            }
        }
    
        public class Item
        {
            public string Text { get; set; }
            public string Value { get; set; }
        }
    }

    View

    @{
        ViewBag.Title = "Contact";
    }
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    
    @Html.DropDownList("Items", null,
            htmlAttributes: new { @class = "form-control" })

    Resultant html code of DropDownList

    Note that Type 2 is selected since "2" is set to selectedValue in the action method above.

    <select class="form-control" id="Items" name="Items">
      <option value="1">Type 1</option>
      <option selected="selected" value="2">Type 2</option>
    </select>

    Important notes:

    (1) The 1st argument of DropDownList method must be the same name of ViewBag set in the action method (i.e., "Items" in the above code) so that the view can find the SelectList from the ViewBag correctly.

    (2) The 2nd argument of DropDownList method must be null. Otherwise the selectedValue set in the action method will be ignored.

    (3) The 1st argument of DropDownList method will be set to the name attribute of select element as shown in the above html source. Threfore, be careful so that the model binding can be performed properly with the name (i.e., "Items" in the above code).

    Friday, January 15, 2021 1:26 AM