我知道我需要通过“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>
}