MVC3 - DropDownListFor不填充

时间:2012-07-14 11:58:51

标签: c# asp.net-mvc-3 html.dropdownlistfor

我已经尝试了一整天,但下拉列表,我无法加载。它应该是一个简单的应用程序。我需要创建一个新的Employee,而创建视图呈现一个下拉列表,其中填充了来自StoresMst表的不同[Store Names]。这个想法是将员工与商店联系起来。以下是我的代码

在viewModel类

    public class EmployeeStoreViewModel
    {
        private JCOperationsDataContext  db = new JCOperationsDataContext ();

        //public Employee employee { get; set; }
        public IEnumerable<SelectListItem> Stores { get;set;}
        public int storeID { get; set; }         
    }

在Create ActionLink

        public ActionResult Create()
        {
            //ViewData["PartialStores"] = repository.GetStoreNames();
            var model = new EmployeeStoreViewModel()
            {   
                //Stores= jc.StoreMsts.OrderBy(o=> o.StoreID).ToList<SelectListItem>();

                Stores = jc.StoreMsts
                        .ToList()
                        .Select(x => new SelectListItem
                        {
                            Text = x.StoreID.ToString(),
                            Value = x.StoreName
                        }),                        
            };

            return View(model);
        }

在视图中(添加了对ModelView类的引用

<div class="editor-field">
    @{Html.DropDownListFor(model => model.storeID, new SelectList (Model.Stores));}
</div >

页面加载时没有错误,但没有渲染和填充DropDownbox。我错过了什么吗?我正在使用MVC3和VS2010 Ultimate 请注意:我尝试使用MVC2,但确实有效。

2 个答案:

答案 0 :(得分:2)

删除DropDownListFor电话中的花括号。在你的代码中,razor将其视为常规方法调用,并忽略方法的返回值。使用razor输出html的正确语法如下。

<div class="editor-field">
    @Html.DropDownListFor(model => model.storeID, new SelectList (Model.Stores))
</div >

答案 1 :(得分:0)

因为您在视图模型中有Stores对象,并且在传入之前设置了该集合,所以您不需要使用“new SelectList”,您只需在集合中引用该属性即可。此外,您不需要在下拉列表周围使用花括号,也不会以这种方式进行评估。这应该是你所需要的:

<div class="editor-field">
@Html.DropDownListFor(model => model.storeID, Model.Stores);
</div >

编辑:再次查看代码后,如果您的下拉列表没有以这种方式加载,您可能需要将集合类型更改为List而不是IEnumerable。