Home > Net >  Populate select tag razor view
Populate select tag razor view

Time:11-24

I'm currently working on an ASP.NET Core MVC project.

I have a view model which contains a list as:

public class CampaignViewModel
{
    public IList<Agency> Agencies { get; set; }
}

In the controller, I assign that list like this:

[HttpGet]
public async Task<IActionResult> Create()
{
    var agencies = await _agenciesService.GetAgenciesAsync();
    var model = new CampaignViewModel { Agencies = agencies };
}

GetAgenciesAsync method:

public async Task<IList<Agency>> GetAgenciesAsync()
{
    return await _db.Agencies
                    .Include(a => a.Address)
                    .Include(pc => pc.PrimaryContact)
                    .Include(ac => ac.AlternateContact)
                    .ToListAsync();
}

Agency model class:

public class Agency
{
    public int AgencyId { get; set; }

    public string Name { get; set; } = string.Empty;
    ...
}

Then in my razor view, I want to render it as:

 @model Lib.ViewModels.Campaigns.CampaignViewModel
<select asp-for="Agencies" asp-items="Model.Agencies" ></select>

When I try to run the project, I get an error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Project.Lib.Models.Agency>' to 'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'. An explicit conversion exists (are you missing a cast?)

How can I solve that? Regards

CodePudding user response:

try to this: Create.cshtml

@model CampaignViewModel

CodePudding user response:

Just as the error indicates,asp-items expects type of IEnumerable<SelectListItem> instead of IEnumerable<Agency>

You could try as below:

<select asp-for="Agencies" asp-items="Model.Agencies.Select(x=>new SelectListItem() { Text=x.Name,Value=x.AgencyId.ToString()})" ></select>

And I tried to pass the viewmodel form controller to view :

var vm = new CampaignViewModel() { Agencies = new List<Agency>() { new Agency() { AgencyId = 1, Name = "SomeName" }, new Agency() { AgencyId = 2, Name = "AnotherName" } } };

The Result:

enter image description here

I don't know why the error Cannot resolve symbol 'Select' occored in your project(I just created an empty MVC project and it works well,don't need refer other namespaces)

Maybe you could try pass the selectListitems from controller to View as below

in controller:

ViewBag.Select = vm.Agencies.Select(x => new SelectListItem() { Text = x.Name, Value = x.AgencyId.ToString() }).ToList();

in View:

asp-items="(List<SelectListItem>)ViewBag.Select"
  • Related