问题描述
我尝试了几种不同的方法.我不确定为什么,但是我的SelectList/DropDown为空.它没有显示数据.我不确定我要去哪里错了.
I've tried a few different approaches. I'm not sure why but my SelectList/DropDown is empty. It shows no data. I'm not sure where I am going wrong.
我有一个ASP.NET Core应用程序.实体框架核心. Db首先.我正在使用存储库模式.
I have an ASP.NET Core App. Entity Framework Core. Db First. I am using a repository pattern.
这是我的模特班
public partial class Commodity
{
public Guid Oid { get; set; }
public string Code { get; set; }
}
这是我的界面
interface ICommodityRepository
{
IEnumerable<Commodity> GetAll();
}
我的存储库:
public class CommodityRepository : ICommodityRepository
{
private ltgwarehouseContext context;
public CommodityRepository()
{ }
public IEnumerable<Commodity> GetAll()
{
return context.Commodity.ToList();
}
}
我的控制器:
public class CommoditiesController : Controller
{
static readonly CommodityRepository commodities = new CommodityRepository();
public CommoditiesController(CommodityRepository commodities)
{ }
// GET: /<controller>/
public IEnumerable<Commodity> CommoditiesList()
{
return commodities.GetAll();
}
}
这是我的视图/HTML标记:
This is my View/HTML Markup:
@model Lansing.BasisMap.Domain.Models.Commodity
<li><select asp-for="@Model.Code" asp-controller="Commodities" asp-action="CommoditiesList"></select> </li>
推荐答案
(我不太熟悉ASP.NET Core中的Tag Helper语法,但是请给我一个机会,如果我愿意的话,请任何人纠正我是错的)
(I'm not too familiar with the Tag Helper syntax in ASP.NET Core, but I'll give it a shot, anyone please correct me if I'm wrong)
-
asp-for=""
属性不需要@
前缀,因为它不是Razor代码,该属性值已经由ASP.NET的解析器处理-仅当您使用的C#语法与HTML(例如,双引号). -
asp-controller
和asp-action
属性不适用于<select>
- 您没有为
<select>
提供任何选项,请使用asp-items
属性并提供IEnumerable<SelectListItem>
或SelectList
实例.可以通过您的ViewModel
或(我的喜好)通过ViewData
(或ViewBag
)传递.
- The
asp-for=""
attribute does not need the@
prefix because it is not Razor code, the attribute value is already handled by ASP.NET's parser - you only need it if you're using C# syntax that is ambiguous with HTML (e.g. double-quotes). - The
asp-controller
andasp-action
attributes do not apply to<select>
- You are not providing any options to your
<select>
, use theasp-items
attribute and provideIEnumerable<SelectListItem>
or aSelectList
instance. This can be passed in through yourViewModel
or (my preference) throughViewData
(orViewBag
).
假设它是ViewData
,然后:
public ActionResult YourControllerAction() {
// stuff
this.ViewData["items"] = commodities
.GetAll()
.Select( c => new SelectListItem() { Text = c.Code, Value = c.Oid.ToString() } )
.ToList();
// stuff
return this.View( viewModel );
}
并在这样的视图中使用它:
And use it in view like this:
<select asp-for="Model.Code" asp-items="@ViewData["items"]" />
此质量检查帖子中还有很多示例:选择标签助手在ASP.NET Core MVC中
There's a lot more examples in this QA posting: Select Tag Helper in ASP.NET Core MVC
这篇关于在ASP.NET Core中的SelectList中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!