0

i have a code below in my controller:

var getAllModel =
            VehicleManager.GetAllModelsByMakeId(getMakeId.MakeId)
                .Select(c => new SelectListItem {Text = c.Name, Value = c.ModelId.ToString()})
                .ToList();
var getAllTrim =
            VehicleManager.GetAllTrimByModelId(getModelId.ModelId)
                .Select(c => new SelectListItem {Text = c.Name, Value = c.TrimId.ToString()}).ToList();

ViewBag.ModelName = getAllModel;
ViewBag.TrimName= getAllTrim;

and in my .cshtml page also below:

var trimName = (IEnumerable<SelectListItem>)ViewBag.ModelName;
var modelName = (IEnumerable<SelectListItem>)ViewBag.TrimName;

Now i want to insert a trimName.Insert(0, new SelectListItem {Text= "Select", Value = ""}) but failed to access.

here's the problem i encountered: Object reference not set to an instance of an object. Anyone has a suggestion or explanation on this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397

3 Answers3

0

Use List<T> instead of IEnumerable<T> as IEnumerable<T> is sequential, From a SO answer:

The purpose of the IEnumerable interface is to allow a consumer to view the contents of a collection. Not to modify the values.

var trimName = (List<SelectListItem>)ViewBag.ModelName;
var modelName = (List<SelectListItem>)ViewBag.TrimName;

See this SO post to know why you cannot add item in IEnumerable<T>

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

If your only goal is to add an empty item to the select list, then there's a much easier way. Html.DropDownListFor takes a parameter to set up an empty item for you:

@Html.DropDownListFor(m => m.TrimName, (IEnumerable<SelectListItem>)ViewBag.TrimNameChoices, "Select an Option...")

Also, notice that I changed the name of your ViewBag variable. If your property on your model is TrimName you can't store your select list in ViewBag.TrimName or it will clobber any selected value. It's always better, if you're going to use ViewBag at all for select lists, to name them with something like Choices or Options at the end, so you don't have to worry about collisions like this.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

Model

[Required]
[Display(Name = "Trim Name")]
public string TrimName{ get; set; }

Controller:

var getAllTrim =
            VehicleManager.GetAllTrimByModelId(getModelId.ModelId)
        .Select(c => new SelectListItem {Text = c.Name, Value = c.TrimId.ToString()})
        .ToList();

ViewBag.TrimList= getAllTrim;

View

@Html.DropDownListFor(model => model.TrimName, 
                  (IEnumerable<SelectListItem>)ViewBag.TrimList, "-- Select --")
meda
  • 45,103
  • 14
  • 92
  • 122