SelectList选择的值未转移到DropDownList

时间:2012-02-13 22:32:24

标签: asp.net-mvc razor

我有一个带有下拉列表的Razor页面:

@using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { @id = "ProductsByOwners" }))
{            
    @Html.Label("Choose product owner: ")
    @Html.DropDownList("OwnerList", (SelectList)ViewBag.OwnerList, new { @onchange = "this.form.submit();" })    
}

我的SelectList的选定值未转移到DropDownList。我已调试并逐步完成代码,发现(SelectList)ViewBag.OwnerList已正确评估并选择了预期值,但生成的HTML中没有选择任何option个标记。

谁能看到我在这里做错了什么?

已更新

以下是我在行动中创建SelectList的方法:

ViewBag.OwnerList = new SelectList(ListUtils.ProductOwners(), "Key", "Value", values["OwnerList"]);

结果的值已由values["OwnerList"]选中。

谢谢!

2 个答案:

答案 0 :(得分:6)

您没有正确使用DropDownList帮助程序。要创建下拉列表,您需要做两件事:

  1. 在提交表单时绑定到所选值的标量属性
  2. 将选项绑定到
  3. 的集合

    在你的例子中,你只有这两件事中的一件(第二件)。您的第一个参数称为OwnerList,并且您将ViewBag.OwnerList作为第二个参数传递。

    所以:

    @Html.DropDownList(
        "SelectedOwnerId", 
        (SelectList)ViewBag.OwnerList, 
        new { @onchange = "this.form.submit();" }
    )
    

    显然我建议你使用强类型视图和视图模型。显然,摆脱了弱类型的ViewBag / ViewData / ViewCrap。

    首先设计一个视图模型以满足视图的要求(从目前为止显示的是显示下拉列表):

    public class OwnerViewModel
    {
        [DisplayName("Choose product owner: ")]
        public string SelectedOwnerId { get; set; }
    
        public IEnumerable<SelectListItem> OwnerList { get; set; }
    }
    

    然后是控制器:

    public class ReportController: Controller
    {
        public ActionResult ProductsByOwners()
        {
            var model = new OwnerViewModel
            {
                // preselect the second owner
                SelectedOwnerId = "2",
    
                // obviously those come from your database or something
                OwnerList = new[] 
                {
                    new SelectListItem { Value = "1", Text = "owner 1" },
                    new SelectListItem { Value = "2", Text = "owner 2" },
                    new SelectListItem { Value = "3", Text = "owner 3" },
                }
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult ProductsByOwners(OwnerViewModel model)
        {
            ...
        }
    }
    

    你有一个相应的强类型视图:

    @model OwnerViewModel
    @using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { id = "ProductsByOwners" }))
    {            
        @Html.LabelFor(x => x.SelectedOwnerId)
        @Html.DropDownListFor(
            x => x.SelectedOwnerId, 
            Model.OwnerList, 
            new { onchange = "this.form.submit();" }
        )
    }
    

答案 1 :(得分:6)

在DDL中未选择所选项目的最常见原因是您已将选择列表命名为与模型相同。 首选强类型视图,但在Viewbag中传递SelectList是精细。请参阅我的教程Working with the DropDownList Box and jQuery和我的博客Cascading DropDownList in ASP.Net MVC