skip to Main Content

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


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search