好的,我已经阅读了一堆文章,但我仍然迷路,所以我想我会把问题放在这里。
我正在尝试在我的“帖子”创建视图中创建一个动态下拉列表。我想从我的 Categories.sdf 中提取 selectList 项目,它有一个名为 categories 的表和两列“CategoryID”和“CategoryTitle”。
我知道我需要通过“postscontroller”将项目拉入视图包中,以便将它们传递给视图。但我不确定这会是什么样子。再说一次,我是 MVC 的新手,所以如果我听起来像个笨蛋,我很抱歉。
好的,我已经阅读了一堆文章,但我仍然迷路,所以我想我会把问题放在这里。
我正在尝试在我的“帖子”创建视图中创建一个动态下拉列表。我想从我的 Categories.sdf 中提取 selectList 项目,它有一个名为 categories 的表和两列“CategoryID”和“CategoryTitle”。
我知道我需要通过“postscontroller”将项目拉入视图包中,以便将它们传递给视图。但我不确定这会是什么样子。再说一次,我是 MVC 的新手,所以如果我听起来像个笨蛋,我很抱歉。
我知道我需要通过“postscontroller”将项目拉入视图包中
哦,不,你不需要做那样的事情。
您可以从定义视图模型开始:
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>
}