我想添加一个带有类别的帖子,我的Add
操作BlogController
是这样的:
private readonly IBlogPostRepository _blogPostRepository;
private readonly ICategoryRepository _categoryRepository;
public BlogController()
{
_blogPostRepository = new BlogPostRepository(new SiteContext());
_categoryRepository = new CategoryRepository(new SiteContext());
}
public BlogController(IBlogPostRepository blogPostRepository, ICategoryRepository categoryRepository)
{
_blogPostRepository = blogPostRepository;
_categoryRepository = categoryRepository;
}
public ActionResult Add()
{
ViewData["categoryList"] = _categoryRepository.GetAllCategory();
return View("Add");
}
[HttpPost]
public ActionResult Add(BlogPost blogPost)
{
if (ModelState.IsValid)
{
blogPost.PublishDate = DateTime.Now;
_blogPostRepository.AddPost(blogPost);
_blogPostRepository.Save();
return RedirectToAction("Add");
}
return new HttpNotFoundResult("An Error Accoured while requesting your order!");
}
我的第一个问题是,为什么我不能将类别列表投射到SelectList
剃刀中以通过 选择类别DropDownList
?我的代码是这样的:
<div>
@Html.LabelFor(b => b.Category)
@Html.DropDownList("Category", ViewData["categoryList"] as SelectList)
@Html.ValidationMessageFor(b => b.Category)
</div>
我的第二个问题是:如何Add
根据POST
请求添加类别?