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.
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.