Home > OS >  Populate a select list ASP.NET Core MVC
Populate a select list ASP.NET Core MVC

Time:10-27

I'm busy with an ASP.NET Core MVC application, and I'm trying to populate a drop down list. I've created a view model and I have added a method to my StoresController that returns a list of stores that I want to display in a dropdown. I've been working off some online tutorials as I'm very new to asp.

View model:

public class StoreListViewModel
{
    public List<StoreList> StoreList { get; set; } = new List<StoreList>();
}

public class StoreList
{
    public string StoreId { get; set; } = null!;
    public string StoreName { get; set; } = null!;
}

StoresController:

public IActionResult LoadStoreList()
{
    if (ModelState.IsValid)
    {
        var storeList = new StoreListViewModel().StoreList.Select
                        (x => new SelectListItem { Value = x.StoreId, Text = x.StoreName }).ToList();
        ViewBag.Stores = storeList;
    }

    return NotFound();
}

I'm trying to use ViewBag to call my LoadStoreList() method.

<select name="storeList"  asp-items="@(new SelectList(ViewBag.Stores, "Value", "Text"))"></select>

When I load my page I get the following error

Value cannot be null. (Parameter 'items')

The page I need the dropdown list on is my CreateUser.cshtml which is bound to my UserModel and has a UsersController. The method I have created for listing the stores is in my StoresController which is bound to my StoresModel. So I'm not sure if that's causing the issue.

I've been battling with this for days, if someone could help me get this working or show me a better method, that would be great.

*Edit

The UserIndex() method is the first method that fires when my users page opens, do I call the LoadStoreList() method from there ?

UserController

public async Task<IActionResult> UsersIndex()
{
      return _context.UsersView != null ? 
                  View(await _context.UsersView.ToListAsync()) :
                  Problem("Entity set 'ApplicationDbContext.Users'  is null.");
}

CodePudding user response:

I'm trying to use ViewBag to call my LoadStoreList() method.

ViewBag cannot be used to call any method. You just need set value for ViewBag in the method which renders your show dropdownlist's page.

From your description, you said the page you need the dropdown list on is CreateUser.cshtml. Assume that you render the CreateUser.cshtml page by using CreateUser action.

CreateUser.cshtml:

<select name="storeList"  asp-items="@(new SelectList(ViewBag.Stores, "Value", "Text"))"></select>

Controller:

public class YourController : Controller
{
    private readonly YourDbcontext _context;
    public YourController(YourDbcontext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult CreateUser()
    {
        var storeList = _context.StoreLists.Select
            (x => new SelectListItem { Value = x.StoreId , Text = x.StoreName }).ToList();
        ViewBag.Stores = storeList;
        return View();
    }
}

YourDbcontext should be something like:

public class YourDbcontext: DbContext
{
    public YourDbcontext(DbContextOptions<MvcProjContext> options)
        : base(options)
    {
    }

    public DbSet<StoreList> StoreLists{ get; set; } 

}

CodePudding user response:

Dont use viewbag for storing list data. Make your view page model including List, for example:

public class UserCreationViewModel{
    public int Id{ get; set; }
    public string Name { get; set; }
    // Any other properties....
     public List<StoreList> StoreList { get; set; }
}

in your controller YourController:

[HttpGet]
public IActionResult CreateUser()
{
    var storeList = new StoreListViewModel().StoreList.Select
                    (x => new SelectListItem { Value = x.StoreId, Text = x.StoreName }).ToList();

    UserCreationViewModel model=new UserCreationViewModel{
      StoreList = storeList
    };    

 return View("createUserViewName", model);
 }

in createUserViewName:

@Html.DropDownList("StoreId", new SelectList(Model.StoreList, "StoreId", "StoreName"), "Select", new { @class = "form-control" })

or

<select  asp-for="@Model.StoreId" asp-items="@(new SelectList(Model.StoreList, "StoreId", "StoreName"))">
    <option value="-1">Select</option>
</select>
  • Related