Home > Back-end >  Populate Dropdownlist from Model in ASP.NET MVC
Populate Dropdownlist from Model in ASP.NET MVC

Time:10-03

I am working on a CRUD ASP.NET Core MVC application. I have two entities Product and Categrory, i want to populate a DropDownlist from model "Category" in the "Product" View. Here is my code:

public class Product
{
    [Key]
    public int ProductId { get; set; }
    
    public string ProductName { get; set; }

    public string Description { get; set; }

    [ForeignKey("CategoryId")]
    public int CategoryId { get; set; }

    public virtual Category Category { get; set; }
}

public class Category
{
    [Key]
    public int CategoryId { get; set; }

    [Required]
    public string CategoryName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

ProductController.cs:

[HttpGet]
    public IActionResult Create()
    {
        List<Category> categories = _dbcontext.Category.ToList();
        ViewBag.bpCategories = new SelectList(categories, "CategoryId", "Category");
        Product product = new Product();
        return View(product);
    }

and in Create.cshtml i used this code to display the Dropdownlist:

        <div >
            <label asp-for="CategoryId" ></label>
            <select asp-for="CategoryId"  asp-items="ViewBag.bpCategories"></select>
        </div>

But this code throws Nullreference exception. Any suggestions??

CodePudding user response:

Maybe an error comes from SelectList constructor. Try this:

 ViewBag.bpCategories = new SelectList(categories, "CategoryId", "CategoryName");

Use "CategoryName" as text value instead of "Category".There is no Category property in your Category class. The third parameter is the data text field. Check here: https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#system-web-mvc-selectlist-ctor(system-collections-ienumerable-system-string-system-string)

  • Related