I want to add a post with category, my Add action in BlogController is like this :
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!");
}
My first question is that why I can’t cast category list to SelectList in razor to select a category via DropDownList? My code in view is like this:
<div>
@Html.LabelFor(b => b.Category)
@Html.DropDownList("Category", ViewData["categoryList"] as SelectList)
@Html.ValidationMessageFor(b => b.Category)
</div>
My second question is: how can I add category in Add action with POST request?
To use a collection for a dropdown, it has to be of type
IEnumerable<SelectListItem>, whichSelectListis. You can’t take an arbitrary collection of objects and just cast it to aSelectList.I like to use an extension method for creating an
IEnumerable<SelectListItem>, check out this:You can then use this extension method in your controller:
Assuming that your
Categoryhas the propertiesIdandName…And then use it in your view:
On a side note, I would recommend that you use models to pass to your (strongly typed) views, as opposed to using
ViewData/ViewBag. It saves you a lot of trouble the day you’re going to refactor something and it also gives you good tooling help (intellisense).