Search code examples
c#asp.net-coreasp.net-core-mvc

How to get dropdown list in edit action .NET Core?


I am trying to display the selected value in the dropdown when call the Edit action. Currently my code displays the following in dropdown list. The value does get display with the @Html method

@Html.EditorFor(model => model.Projectname)

However what I am trying to achieve is that should be able bring the selected value with the dropdown list. I did try to store the dropdown list in a ViewBag, but it displays WebDSR.Models.DTO.Project.

Instead it should display the project name - the values from database as selected

Amazon
Walmart 
Myntra

Controller action method:

public IActionResult Edit(int id)
{
    ViewBag.Project = new SelectList(db.Defects
                                       .Where(x => x.DefectId == id)
                                       .Select(x => new Project() { ProjectId = x.ProjectId, ProjectName = x.ProjectName}));
    return View(db.Defects.Find(id));
}

View

<select asp-items="ViewBag.Project" class="form-control"></select>

Any help is much appreciated.


Solution

  • Since you are providing the IEnumerable list of your model class type instead of IEnumerable<SelectListItem>, you need to specify the properties names for the option value and label according to SelectList(IEnumerable, String, String).

    ViewBag.Project = new SelectList(
        db.Defects
            .Select(x => new Project() { ProjectId = x.ProjectId, ProjectName = x.ProjectName }),
        nameof(Project.ProjectId),
        nameof(Project.ProjectName)
    );
    

    In the Razor page, you are missing the @ to refer to the ViewBag.Project.

    @model YourModel
    
    <select asp-items="@ViewBag.Project" class="form-control" asp-for="Id"></select>