Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9270079
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T15:17:00+00:00 2026-06-18T15:17:00+00:00

I want to add a post with category, my Add action in BlogController is

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T15:17:02+00:00Added an answer on June 18, 2026 at 3:17 pm

    To use a collection for a dropdown, it has to be of type IEnumerable<SelectListItem>, which SelectList is. You can’t take an arbitrary collection of objects and just cast it to a SelectList.

    I like to use an extension method for creating an IEnumerable<SelectListItem>, check out this:

    public static class SelectListExtensions
    {
        public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> source)
        {
            return ToSelectList(source, null);
        }
    
        public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> source, string defaultOption)
        {
            return ToSelectList(source, value => value, value => value.ToString(), null);
        }
    
        public static IEnumerable<SelectListItem> ToSelectList<T, TDataValue>(
            this IEnumerable<T> source,
            Func<T, TDataValue> dataValueSelector,
            Func<T, string> dataTextSelector)
        {
            return ToSelectList(source, (value, index) => dataValueSelector(value), dataTextSelector, null);
        }
    
        public static IEnumerable<SelectListItem> ToSelectList<T, TDataValue>(
            this IEnumerable<T> source,
            Func<T, int, TDataValue> dataValueSelector,
            Func<T, string> dataTextSelector)
        {
            return ToSelectList(source, dataValueSelector, dataTextSelector, null);
        }
    
        public static IEnumerable<SelectListItem> ToSelectList<T, TDataValue>(
            this IEnumerable<T> source,
            Func<T, TDataValue> dataValueSelector,
            Func<T, string> dataTextSelector,
            string defaultOption)
        {
            return ToSelectList(source, (value, index) => dataValueSelector(value), dataTextSelector, defaultOption);
        }
    
        public static IEnumerable<SelectListItem> ToSelectList<T, TDataValue>(
            this IEnumerable<T> source,
            Func<T, int, TDataValue> dataValueSelector,
            Func<T, string> dataTextSelector,
            string defaultOption)
        {
            var list = source.Select((item, index) => new SelectListItem
            {
                Value = dataValueSelector(item, index).ToString(),
                Text = dataTextSelector(item),
            }).ToList();
    
            if (defaultOption == null) return list;
    
            list.Insert(0, new SelectListItem { Text = defaultOption, Value = "-1" });
    
            return list;
        }
    }
    

    You can then use this extension method in your controller:

    public ActionResult Add()
    {
        ViewData["categoryList"] = _categoryRepository.GetAllCategory()
            .ToSelectList(c => c.Id, c => c.Name);
    
        return View("Add");
    }
    

    Assuming that your Category has the properties Id and Name…

    And then use it in your view:

    @Html.DropDownList("Category", ViewData["categoryList"] as IEnumerable<SelectListItem>)
    

    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).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a scraping object basically. I want to be able to add POST
I want to know how to add a new submenu for a custom post
I want add new Feed item on entity persist and update. I write this
I want add my custom sidebar next right column all page. Please check this
I have a link in a page that goes like this: Url.Action(List, Item, new
I'm using this piece of code I found ( http://impnerd.com/wordpress-hack-add-post-images-to-your-homepage ) to display the
I only want the latest post from the category to be excluded from the
I have a function that looks like this: def post_count(self): return self.thread_set.aggregate(num_posts=Count('post'))['num_posts'] I only
When I add category in controller action I return JSON object: return Json(new {
I want add UIGestureRecognizerDelegate to UIWebView,but failed. if [self.view addsubView:webView]; So UIWebView is ok,but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.