我知道我需要通過「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>
}
你的問題是? – VJAI