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 class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Warehouse" class="control-label"></label>
<select asp-for="Warehouse" class ="form-control" asp-items="ViewBag.Warehouses"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
I heard something about ViewBag being bad practice, is that correct?
3
Answers
You may use sub properties on your view model, or just use viewdata.
Not sure about viewbag. But probably it may help.
https://learn.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://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-6.0#summary-of-the-differences-between-viewdata-and-viewbag
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:
The above code will also assign your choice to a property called
SelectedWarehouse
in your Category view model.I use Select List in my projects.
I think the following two links can help you.
Good luck
https://www.c-sharpcorner.com/article/net-core-5-dropdownlist/
https://www.compilemode.com/2021/06/dropdown-list-in-asp-net-core-mvc.html