ASP.NET MVC-如何将列表从控制器传递到填充下拉列表?
我为“类别”模型有一个“创建”视图,该视图应允许用户选择仓库(另一个模型),其中将存储“类别”(使用下拉列表)。由于我无法将2个ViewModels传递给单个视图,因此如何在类别中访问仓库名称。创建视图?
@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>
我听说了有关ViewBag是不良习惯的消息,这是正确的吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在视图模型上使用子属性,也可以使用ViewData。
不确定ViewBag。但可能会有所帮助。
viewData和ViewData和ViewData
< a href =“ https://lealen.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=peive = asspnetcore-6.0#summary-ombary-off-the-differences-the-differences-betwiend-betwiend-betwiend-betwiend-viewdata-and-viewdata-and-viewbag” rel =“ nofollow noreferrer”> https://lealen.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=peaspnetcore-6.0#summary-of-the-summary-of-the-differences-betweienc-betweik-betwiewdata-viewdataa------ -ViewBag
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
如果您可以在类别视图模型中包含一个新属性,请考虑包含仓库名称列表。
您可以在视图中使用以下代码在下拉列表中显示仓库名称:
以上代码还将您的选择分配给您的类别视图模型中的名为
selectedwarehouse
的属性。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.我在项目中使用选择列表。
我认为以下两个链接可以为您提供帮助。
祝你好运
https://www.c-cc-sharpcorner.com/article.com/article.com/article /net-core-5-dropdownlist/
https://www.compilemode.com/2021/06/dropdown-list-list-in-asp-net-core-mvc.html
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