How to set selected value in mvc dropdown list

I have a dropdown menu View

@Html.DropDownList("GenderAllowed", (SelectList)ViewBag.LocGenederAllowedList, new { @class = "form-control" })

      

and i am sending the dropdown list via ViewBag

, and via the model i am sending the value to be selected in the dropdown.

But no value is selected in the dropdown menu.

My controller

[HttpGet]
    public ActionResult EditVendorLocation(int VendorLocationID)
    {
        VendorLocationHandler obj = new VendorLocationHandler();
        LocationGrid objLoc = new LocationGrid();
        FillGenederAllowed(objLoc);
        objLoc = obj.GetVendorLocationForAdmin(VendorLocationID);

        return View(objLoc);
    }

      

Function for Viewbag

public void FillGenederAllowed(LocationGrid V)
{
    Dictionary<int, string> LocGenederAllowed = EnumHelper.GetGenderStates();
    SelectList LocGenederAllowedList = new SelectList(LocGenederAllowed, "key", "value");
    ViewBag.LocGenederAllowedList = LocGenederAllowedList;
}

      

+3
c # model-view-controller asp.net-mvc html-select


source to share


4 answers


SelectListItems

passed to DropDownList has a property Selected

. In the ViewModel, set this value to true for the element that should be selected first.



+1


source to share


You can do this in your controller action as shown below. Hope it helps.

ViewBag.LocGenederAllowedList = new SelectList(items, "Id", "Name", selectedValue);

      



dot net fiddle link: https://dotnetfiddle.net/PFlqei

0


source to share


Check out this class. All you have to do is instantiate them and set the property Selected

to true for the element you want to select initially:

public ActionResult YourActionMethod(...)
{
    var selectItems = Repository.SomeDomainModelObjectCollection
      .Select(x => new SelectListItem {
        Text = x.SomeProperty,
        Value = x.SomeOtherProperty,
        Selected = ShoudBeSelected(x)
    });
    ViewBag.SelectListItems = selectItems;
    // more code
    var model = ...; // create your model
    return View(model);
}

      

You will need this overload Html.DropDownListFor(...)

in order to use this .

0


source to share


This is needed in the controller

   ViewBag.LocGenederAllowedList = 
       new SelectList(db.SomeValues, "Value", "Text",selectedValue);

      

And in your opinion

            @Html.DropDownList("GenderAllowed", 
         (SelectList)ViewBag.LocGenederAllowedList, new { @class = "form-control" })

      

0


source to share







All Articles