Home > Back-end >  ASP.NET MVC - How to pass a list from controller to view to populate dropdown?
ASP.NET MVC - How to pass a list from controller to view to populate dropdown?

Time:06-22

I have a "Create" view for my "Category" model which should allow the user to select the Warehouse (another model) where the "Category" will be stored (using a dropdown). As I cannot pass 2 viewmodels to a single view, how can I access the Warehouse names inside my Category.Create view?

@model InventoryManSys.Models.Category

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Category</h4>
<hr />
<div >
    <div >
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" ></div>
            <div >
                <label asp-for="Name" ></label>
                <input asp-for="Name"  />
                <span asp-validation-for="Name" ></span>
            </div>
            <div >
                <label asp-for="Warehouse" ></label>
                <select asp-for="Warehouse" class ="form-control" asp-items="ViewBag.Warehouses"></select> 
            </div>
            <div >
                <input type="submit" value="Create"  />
            </div>
        </form>
    </div>
</div>

I heard something about ViewBag being bad practice, is that correct?

CodePudding user response:

You may use sub properties on your view model, or just use viewdata. Not sure about viewbag. But probably it may help.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-6.0#pass-data-to-views

Summary of the differences between ViewData and ViewBag

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-6.0#summary-of-the-differences-between-viewdata-and-viewbag

CodePudding user response:

If you can include a new property in your Category view model, consider including a List of warehouse names.

You can use the following code in your view to show warehouse names in a dropdown list:

@Html.DropDownListFor(model => model.SelectedWarehouse, new SelectList(Model.WarehouseNames))

The above code will also assign your choice to a property called SelectedWarehouse in your Category view model.

  • Related