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 6333707
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T18:31:02+00:00 2026-05-24T18:31:02+00:00

I have next model (simplified): public class CarType { public int Id { get;

  • 0

I have next model (simplified):

public class CarType
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

public class Car
{
    [Required]
    public string Model { get; set; }

    [Required]
    public CarType Type { get; set; }

    [Required]
    public decimal Price { get; set; }
}

I want let user to choose car type from the drop-down list on the Create page.
I tried to pass the dictionary of types from database and their names through ViewBag:

ViewBag.Types = _context.CarTypes.ToDictionary(carType => carType.Name);

and select it in the page:

@Html.DropDownListFor(model => model.Type, new SelectList(ViewBag.Types, "Value", "Key"))

But in the POST method I always get constructed Car object with null in Type property.

[HttpPost]
public ActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
        _context.Cars.Add(car);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(car);
}

Is it possible to select custom objects with DropDownList? Because selecting values like int, string works fine.

I had an idea to write ViewModel with int ID instead of CarType and find Type by ID before saving to database. But in that way I need to duplicate all Car properties and their attributes to my ViewModel and in the end – copy all values to the new Car object. For small class its maybe OK, but for some more complex – don’t think so…

This is a small example. What is the common approach to solve such problems? How to write flexible and simple code?

  • 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-05-24T18:31:03+00:00Added an answer on May 24, 2026 at 6:31 pm

    Here’s a trusty HtmlHelper extension method I use for these occassions:

    public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, SelectListItem initialItem)
        where TProperty : struct
    {
        if (!typeof(TProperty).IsEnum)
            throw new ArgumentException("An Enumeration type is required.", "enum");
    
        IList<SelectListItem> items = Enum.GetValues(typeof(TProperty)).Cast<TProperty>()
                .Select(t => new SelectListItem { Text = (t as Enum).GetDescription(), Value = t.ToString() }).ToList();
    
        if (initialItem != null)
            items.Insert(0, initialItem);
    
        return SelectExtensions.DropDownListFor<TModel, TProperty>(helper, expression, items, null, null);
    }
    

    Which will let you write code like this:

    @Html.DropDownListForEnum(model => model.Type)
    

    And give you a fully populated select element with the passed in Type selected.

    The above method can be extended with htmlAttributes and whatever else, but it’s a good start

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

Sidebar

Related Questions

I have two models like so: class Visit(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=65535,
I have next tables Order , Transaction , Payment . Class Order has some
I have a model for which I want to retrieve the next record(s) and
I have the next code: IUnitOfWork factory = DI.Get<IUnitOfWork>(); ISession session = (ISession)ReflectionUtils.GetPropertyValue(factory, Session);
I have a model like this class Parent < ActiveRecord::Base :has_many :kids end class
I have the following model associations: class Product < ActiveRecord::Base has_many :prices class Price
I want to declare next type: <partCode negation=true|false>\*|[0-9]{1,9}</name> with boolean attribute, and text-only content,
I have this model I'm showing in the admin page: class Dog(models.Model): bark_volume =
Say I have the next model: STATUS_CHOICES = ( (0, 'open'), (1, 'close'), )
I have a model # == Schema Information # # Table name: posts #

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.