user4102564
user4102564

Reputation: 33

how to set the selected value in dropdownlist mvc

I have a dropdown in View

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

and I am sending list of dropdown through ViewBag, and through model I am sending value that need to be selected in the dropdown.

But the value in dropdown is not selected.

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;
}

Upvotes: 3

Views: 7819

Answers (4)

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can do it in your controller action like following. Hope it helps.

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

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

Upvotes: 0

Bal&#225;zs
Bal&#225;zs

Reputation: 2929

Take a look at this class. All you need to do is create instances of them and set the Selected property to true for the item you want to be initially selected:

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 of Html.DropDownListFor(...) in order to use this.

Upvotes: 0

Bellash
Bellash

Reputation: 8184

You need this in your controller

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

And in your view

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

Upvotes: 0

Georg Patscheider
Georg Patscheider

Reputation: 9463

The SelectListItemsyou are passing to the DropDownList have a property Selected. In your ViewModel, set this to true for the item that should be selected initially.

Upvotes: 1

Related Questions