Search code examples
c#asp.net-coremodel-view-controllerviewbag

display attribute from model by its primary key with ViewBag and asp-items in mvc asp.net application


I'm building a simple application with ASP.NET MVC. I made two models (Class and Checklist) and Checklist class is supossed to have an m-1 relationship to Class class. I used EF Core to generate the database and the code of the controllers and the views. Specifically, I'm interested in the Create view of my Checklist model, since it has this foreign key that points to Class. The form includes a field as follows:

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

Being ClassId the foreign key. When I add an item in the Create Class form, now it displays just the PK of that item in this select element. I wanted to know if there's any way in which I can display the name of the Class object, not just its ID.

I tried using ViewBag.Name in the asp-items tag helper but it doesn't work. Please let me know if I need to add some code within options tags, but if so, how can I access that information from my Controller. Here's a piece of code of my Checklist controller:

// GET: Checklists
    public async Task<IActionResult> Index()
    {
        var applicationDbContext = _context.Checklist.Include(c => c.Class);
        return View(await applicationDbContext.ToListAsync());
    }

Do I need to modify some code here as well in order to have the names of the Class items?

Please notice that I just want to display this info for UI purposes, but when inserting the item, I want it to insert the row with the ID, since this is how the database and the models were built.

Thank you!


Solution

  • You can add following code in your Create method:

     public IActionResult Create()
        {         
            ViewData["ClassId"] = new SelectList(_context.Class, "Id", "Name");
            return View();
        }