0
 @model ProjectName.Models.ViewModel
 var abc = (IEnumerable<SelectListItem>)ViewData["abc"]; 

The abc stores all retrieved records and then it displays them via the following html tag:

@Html.DropDownList("abcID", abc , "Select abc ", new { @class = "form-control",  required = "required" })

I need to set default value for abcId inside the @Html.DropDownList. How can I do it?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

You can refer to the link,Here is a demo worked:

Controller:

public IActionResult SendReport()
        {
            List<SelectListItem> listAdmin = new List<SelectListItem>();

            listAdmin.Add(
            new SelectListItem
            {
                Text = "admin1",
                Value = "1"
            });
            listAdmin.Add(
            new SelectListItem
            {
                Text = "admin2",
                Value = "2"
            });
            ViewBag.listAdmin = listAdmin;
            //ViewData["listAdmin"] = listAdmin;
            Admin admin = new Admin { id = "2", name = "admin2" };
            return View(admin);
        } 

Admin.cs:

public class Admin
    {
        public string id { get; set; }
        public string name { get; set; }
    }

View:

@model Admin
@{
    ViewData["Title"] = "SendReport";
}

<h1>View</h1>
<div>
    @Html.DropDownListFor(Model => Model.id, new SelectList((IEnumerable<SelectListItem>)ViewBag.listAdmin, "Value", "Text", Model.id), "Selecte", new { @class = "form-control", required = "required" })
</div>

Result: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22