mvc 3动态类别下拉列表

时间:2012-06-13 05:49:54

标签: asp.net-mvc-3 drop-down-menu

好的,我已经阅读了很多文章,但我仍然输了,所以我想我会在这里提出问题。

我正在尝试在“posts”创建视图中创建动态下拉列表。我想从我的Categories.sdf中提取selectList项,它有一个名为categories和两列的表,“CategoryID”和“CategoryTitle”。

我知道我需要通过“postscontroller”将项目拉入viewbag中,以便将它们传递给视图。但我不确定这会是什么样子。再说一次,我是MVC的新手,所以如果我听起来像是一个涂料,我道歉。

1 个答案:

答案 0 :(得分:1)

  

我知道我需要通过“postscontroller”将项目拉入viewbag

哦不,你不需要做那样的事情。

您可以从定义视图模型开始:

public class PostViewModel
{
    [DisplayName("Select a category")]
    [Required]
    public string SelectedCategoryId { get; set; }

    public IEnumerable<SelectListItem> Categories { get; set; }
}

您将在控制器中填充:

public class PostsController: Controller
{
    public ActionResult Index()
    {
        var model = new PostViewModel();
        model.Categories = db.Categories.ToList().Select(c => new SelectListItem
        {
            Value = c.CategoryId,
            Text = c.CategoryName
        });
        return View(model);
    }
}

然后有一个相应的强类型视图(~/views/posts/index.cshtml):

@model PostViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.SelectedCategoryId)
    @Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories, "-- select --")
    @Html.ValidationMessageFor(x => x.SelectedCategoryId)

    <button type="submit">OK</button>
}