首先我想说我是这方面的新手,我的背景是 asp web 表单,我正在尝试将我的技能更新到最新的开发语言。
我有一个 View 需要访问多个模块,所以我创建了一个 View 模型并将其传递给 View 。我的问题是当我尝试从 View 模型访问列表以填充选择(下拉列表)时。我不断收到错误消息。下面是我的 View 模型:-
public class CustomerDetailsViewModel
{
public Customer customer { get; set; }
public IEnumerable<Lookups> titles { get; set; }
public List<Lookups> ePCs { get; set; }
public List<Lookups> jobStages { get; set; }
}
下面是我的选择控件代码。我在尝试访问标题列表时遇到错误。
<div class="form-group">
<label asp-for="customer.Title_Id" class="col-sm-2 col-md-4 col-form-label">Title</label>
<select app-for="Title_Id" asp-items="@(new SelectList(titles,"PK_Id","Description"))"></select>
</div>
最佳答案
既然你已经创建了一个 View 模型,我假设你的 View 有 @model
指令:
@model CustomerDetailsViewModel
当您将 View 模型从 Controller 传递到 View 时,可以通过 Model
属性在 View 中访问它。
asp-for
标签助手不需要 Model
属性,它是隐式的。另一方面,asp-items
不是那样工作的,它需要 Model
前缀:
<select asp-for="customer.Title_Id"
asp-items="@(new SelectList(Model.titles,"PK_Id","Description"))">
</select>
此外,由于您所有的 View 模型属性都是public
,因此命名约定是使用PascalCase
名称:
public class CustomerDetailsViewModel
{
public Customer Customer { get; set; }
public IEnumerable<Lookups> Titles { get; set; }
public List<Lookups> EPCs { get; set; }
public List<Lookups> JobStages { get; set; }
}
关于c# - ASP.Net Core MVC 从 Select 控件的 View 访问 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67902380/