如何从ViewBag数据源向DropDownList添加一个特定项?

时间:2012-08-16 14:43:36

标签: asp.net-mvc-3

我正在尝试修复现有应用程序中的错误,并且我的MVC ViewBag技能有限。首先,我没有时间重构并将ViewBag中的代码更改为ViewModel,尽管这是我的首选方法。

我想从ViewBag中的对象填充DropDownList。代码在这里:

if(Model != null && Model.WarehouseId != null && !Model.WarehouseId.Equals(String.Empty))                
{
    @Html.DropDownListFor(m => m.WarehouseId, (IEnumerable<SelectListItem>)ViewBag.WarehouseCodes)<br /> //<---
}
else
{
    @Html.DropDownListFor(m => m.WarehouseId, (IEnumerable<SelectListItem>)ViewBag.WarehouseCodes, "")<br /> 
}

如果WarehouseID不是String.Empty,我只想将该值加载到DropDownList中。我愿意接受这个问题的C#或jQuery答案。

提前感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:0)

  

我的MVC ViewBag技能有限

如果你忘记了这些技能,那对你来说会更好。开玩笑,为了了解ASP.NET MVC应用程序中的,它们可能很有用: - )

反正:

if (Model != null && Model.WarehouseId != null && !Model.WarehouseId.Equals(String.Empty))                
{
    @Html.DropDownListFor(
        m => m.WarehouseId, 
        ((IEnumerable<SelectListItem>)ViewBag.WarehouseCodes).Where(x => x.Value == Model.WarehouseId.Value)
    )
    <br />
}
else
{
    @Html.DropDownListFor(
        m => m.WarehouseId, 
        (IEnumerable<SelectListItem>)ViewBag.WarehouseCodes, 
        ""
    )
    <br /> 
}

另一种方法是在控制器操作中处理这种情况:

public ActionResult Index()
{
    SomeModel model = ...
    IEnumerable<SelectItem> warehouseCodes = ...
    ViewBag.HasValue = false;
    if (model != null && model.WarehouseId != null && !string.IsNullOrEmpty(Model.WarehouseId.Value))
    {
        warehouseCodes = warehouseCodes.Where(x => x.Value == model.WarehouseId.Value);
        ViewBag.HasValue = true;
    }
    ViewBag.WarehouseCodes = warehouseCodes;
    return View(model);
}

在您的视图中,您现在可以将if替换为:

@Html.DropDownListFor(
    m => m.WarehouseId, 
    (IEnumerable<SelectListItem>)ViewBag.WarehouseCodes, 
    ViewBag.HasValue ? (string)null : ""
)