繁体   English   中英

如何在dropdownlist mvc中设置所选值

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

我在View有一个下拉列表

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

我正在通过ViewBag发送下拉列表,并通过模型我发送需要在下拉列表中选择的值。

但是未选择下拉列表中的值。

我的控制器

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

        return View(objLoc);
    }

Viewbag的功能

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

传递给DropDownList的SelectListItems具有Selected属性。 在ViewModel中,对于最初应选择的项目,将其设置为true。

您可以在控制器操作中执行此操作,如下所示。 希望能帮助到你。

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

dot net fiddle链接: https//dotnetfiddle.net/PFlqei

看看堂课。 您需要做的就是创建它们的实例,并为您最初选择的项目将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);
}

您将需要Html.DropDownListFor(...)这个重载才能使用

你需要在控制器中使用它

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

在你看来

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

暂无
暂无

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

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