4

I am able to retrieve values from my database and display in the dropdownlist but I want to make it to have a selected value whereby my database has the ID value on it.

Here's my code:

AdminViewModel.cs

public IEnumerable<UserType> UserTypes { get; set; }
public int userTypeID { get; set; }

Controller

var userType = _context.UserTypes.ToList();
var viewModel = new AdminViewModel()
{
     UserTypes = userType
 };
 return View(viewModel);

View

@Html.DropDownListFor(m => m.userTypeID, new SelectList(Model.UserTypes, "userTypeID", "userTypeName", Model.userTypeID), new { @class = "form-control" })

Selected value should be Caregiver based on the database value:

Matheus Cuba
  • 2,068
  • 1
  • 20
  • 31
Snoopy
  • 41
  • 2

1 Answers1

2

Use SelectListItem instead and set the value true for selected item.

AdminViewModel.cs:

public IEnumerable<SelectListItem> UserTypes { get; set; }
public int userTypeID { get; set; }

Controller:

var viewModel = new AdminViewModel();
SelectListItem item;
var userType = _context.UserTypes.ToList();
foreach(var uType in userType)
  {
   item = new SelectListItem();
   item.Text = userType.userTypeName;
   item.Value = userType.userTypeID;
   if (item.Text == "Caregiver") // or any logic
     {
       item.Selected = true;
     }
     viewModel.UserTypes.Add(item);
   }

 return View(viewModel);

View:

@Html.DropDownListFor(m => m.userTypeID, Model.UserTypes , "Select", new { @class = "form-control" })
Anadi
  • 744
  • 9
  • 24
  • Wrong. This is exactly the same as what OP is already doing (internally that is what the `SelectList` constructor does). And the `Selected` proeprty is ignored when binding to a property. –  Mar 05 '18 at 22:10
  • Then please explain the right way..@steph muecke – Anadi Mar 06 '18 at 06:40
  • Read the duplicate :) –  Mar 06 '18 at 06:42
  • Hello I've try this code it still displaying the same as my first post screenshot. [link](https://i.stack.imgur.com/HSRIs.png) – Snoopy Mar 08 '18 at 13:23