简体   繁体   English

如何在dropdownlist mvc中设置所选值

[英]how to set the selected value in dropdownlist mvc

I have a dropdown in View 我在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. 我正在通过ViewBag发送下拉列表,并通过模型我发送需要在下拉列表中选择的值。

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 Viewbag的功能

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

The SelectListItems you are passing to the DropDownList have a property Selected . 传递给DropDownList的SelectListItems具有Selected属性。 In your ViewModel, set this to true for the item that should be selected initially. 在ViewModel中,对于最初应选择的项目,将其设置为true。

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 dot net fiddle链接: https//dotnetfiddle.net/PFlqei

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: 您需要做的就是创建它们的实例,并为您最初选择的项目将Selected属性设置为true:

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 . 您将需要Html.DropDownListFor(...)这个重载才能使用

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" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM