Search code examples
c#asp.net-mvchtml.dropdownlistforpopulateselectedvalue

set value of dropdownlist based on value from database in asp.net mvc5


I have declared a SelectListItem object in my controller, I able to populate them into my DropDownList in Create() page, however I am having problem trying to get value from model to set the selected value of the DropDownList in Edit() page.

Code of Create() in controller:

public ActionResult Create()
    {
        var tagList = new List<SelectListItem>();
        tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
        tagList.Add(new SelectListItem() { Text = "Promo", Value = "Promo" });
        tagList.Add(new SelectListItem() { Text = "Limited", Value = "Limited" });
        tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
        tagList.Add(new SelectListItem() { Text = "New", Value = "New" });

        var catList = new List<SelectListItem>();
        catList.Add(new SelectListItem() { Text = "Men", Value = "Men" });
        catList.Add(new SelectListItem() { Text = "Women", Value = "Women" });
        catList.Add(new SelectListItem() { Text = "Sport", Value = "Sport" });
        catList.Add(new SelectListItem() { Text = "Casual", Value = "Casual" });

        var statusList = new List<SelectListItem>();
        statusList.Add(new SelectListItem() { Text = "Available", Value = "Available" });
        statusList.Add(new SelectListItem() { Text = "Unavailable", Value = "Unavailable" });

        ViewBag.tagDropDown = tagList;
        ViewBag.catDropDown = catList;
        ViewBag.statusDropDown = statusList;
        return View();
    }

I am able to populate the DropDownList in Create() view page using all the Viewbag(s).

However now I wished to populate the DropDownList in Edit() view page at the same time set selected value from the model.

Below are the codes from Edit() view page:

<div class="form-group">
        @Html.LabelFor(model => model.category, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.category, new SelectList(ViewBag.catDropDown, "value", "text"), htmlAttributes: new { @class = "form-control" })
        </div>
</div>

Solution

  • All you need to do is to set the category property value of your view model object in your Edit action method.

    public ActionResult Edit(int id)
    {
      var vm=new YourViewModel();
      vm.category="Sport";   // Replace this hard coded value with value from db
      // to do : Load ViewBag.catDropDown
      return View(vm);
    }
    

    Now the DropDownListFor helper method will make the option "Sport" selected, assuming your view is strongly typed to YourViewModel