-1

Im populating a dropdownlist from a table, and the problem is when I go to the Edit page, it didnt select the value but instead show "Select Company".

Im using AspNetUsers default table, and add another column on it called Company (Integer).enter image description here
I have another model & Table called TBL_COMP which map to AspNetUsers.

 public class TBL_COMP
{
    [Key]
    public int CompId { get; set; }
    public string CompDesc { get; set; }
}


In my models (UserViewModels) I have this

    public int Company { get; set; }

    [ForeignKey("Company")]
    public TBL_COMP TBL_COMP { get; set; }

This is the dropdownlist in view:

@Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Company, "Value", "Text"), "Select Company", new { @class = "form-control" })

and this is the controller:

ViewBag.Company = new SelectList(db.TBL_COMP.ToList(), "CompId", "CompDesc", user.Company);
tereško
  • 58,060
  • 25
  • 98
  • 150
Waller
  • 433
  • 1
  • 6
  • 20
  • Possible duplicate of [Can the ViewBag name be the same as the Model property name in a DropDownList?](https://stackoverflow.com/questions/37161202/can-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist) –  Nov 07 '18 at 09:18

1 Answers1

0

The ViewBag.Company is already contained SelectList, just cast it on the view (creating another SelectList from existing SelectList is pointless):

@Html.DropDownListFor(m => m.Company, ViewBag.Company as SelectList, "Select Company", 
                      new { @class = "form-control" })

Or use strongly-typed IEnumerable<SelectListItem> instead:

Viewmodel

public class UserViewModels
{
    // other properties

    public List<SelectListItem> Companies { get; set; }
}

Controller action

var model = new UserViewModels();

model.Companies = db.TBL_COMP.Select(x => new SelectListItem { Text = x.CompDesc, Value = x.CompId }).ToList();

View

@Html.DropDownListFor(m => m.Company, Model.Companies, "Select Company", new { @class = "form-control" })
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61