Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Populate Dropdownlist from Model in ASP.NET MVC

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

But this code throws Nullreference exception. Any suggestions??

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading