EN VI

C# - Error on binding model to Select in ASP.NET Core?

2024-03-10 06:30:05
How to C# - Error on binding model to Select in ASP.NET Core

I'm having some trouble identifying why this is wrong.

Basically, I have a view model which passes the data to the view. But I get an error when I try to bind it using the asp-items tag helper.

View model looks like this:

using Microsoft.AspNetCore.Mvc.Rendering;
using NVFlexo.Models;

namespace NVFlexo.ViewModels;

public class ItemAndItemCategoriesViewModel
{
    public Item Item { get; set; }
    public IEnumerable<ItemCategory> ItemCategories { get; set; }
}

This is the controller method that loads the data:

public IActionResult Create()
{
    ItemAndItemCategoriesViewModel itemAndItemCategories = new ItemAndItemCategoriesViewModel();
    itemAndItemCategories.ItemCategories = _itemCategoriesService.getAllCategories();
    return View(itemAndItemCategories);
}

The relevant part of the view is as below:

@using NVFlexo.ViewModels;

@model ItemAndItemCategoriesViewModel;

@{
    ViewBag.Title = "Create New Item";
    Layout = "_Layout";
}

<form method="post">
...
<div class="mb-3">
   <label asp-for="Item.ItemCategory"></label>
   <select asp-for="Item.ItemCategoryId" class="form-control" asp-items="Model.ItemCategories"></select>
   <span asp-validation-for="Item.ItemCategory" class="text-danger"></span>
</div>
...
</form>

I'm getting this error:

Error CS0266 : Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<NVFlexo.Models.ItemCategory>' to 'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'. An explicit conversion exists (are you missing a cast?)

Appreciate any help as I have been banging my head against this for about 2 days.

Solution:

The exception indicates Model.ItemCategories property is not an IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>.

You could use a SelectList:

<select asp-for="Item.ItemCategoryId" class="form-control" 
  asp-items="@(new SelectList(Model.ItemCategories, "ItemCategoryId", "ItemCategory"))">
</select>

Or, you could change Model.ItemCategories:

    public class ItemAndItemCategoriesViewModel
    {
        public Item Item { get; set; }
        public IEnumerable<SelectListItem> ItemCategories { get; set; }
    }

And set ItemCategories like so:

   var itemCategories = _itemCategoriesService.getAllCategories();
   itemAndItemCategories.ItemCategories = itemCategories.Select(i => 
     new SelectListItem { Value = i.ItemCategoryId, Text = i.ItemCategory });
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login