C# MVC6选择标记帮助器&;导航属性

C# MVC6选择标记帮助器&;导航属性,c#,asp.net-core-mvc,tag-helpers,C#,Asp.net Core Mvc,Tag Helpers,我有一个与另一个有关系的模型类,如下所示: public class Client { public int ID { get; set; } [StringLength(30, ErrorMessage = "Client name cannot be longer than 30 characters.")] public string Name { get; set; } public virtual Industry Industry { get; set

我有一个与另一个有关系的模型类,如下所示:

public class Client
{
    public int ID { get; set; }
    [StringLength(30, ErrorMessage = "Client name cannot be longer than 30 characters.")]
    public string Name { get; set; }
    public virtual Industry Industry { get; set; }
    [Display(Name="Head Office")]
    public string HeadOffice { get; set; }
}

public class Industry
{
    public int ID { get; set; }
    [StringLength(30, ErrorMessage = "Industry name cannot be longer than 30 characters.")]
    [Display(Name="Industry")]
    public string Name { get; set; }
}
最终目标是,在客户端CRUD视图上,我还可以选择Industry.Name,或者在编辑/创建时分配它

我已使用控制器中的以下命令选择下拉列表数据:

private void PopulateIndustriesDropDownList(object selectedIndustry = null)
{
    var industriesQuery = from i in _context.Industry
                          orderby i.Name
                          select i.Name;
    ViewBag.Industries = new SelectList(industriesQuery, "Industry", "Name", selectedIndustry);
}
我的每个控制器功能都有以下功能:

// GET: Clients/Create
public IActionResult Create()
{
    PopulateIndustriesDropDownList();
    return View();
}

// POST: Clients/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Client client)
{
    if (ModelState.IsValid)
    {
        _context.Client.Add(client);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    PopulateIndustriesDropDownList();
    return View(client);
}
一切似乎都正常,但我不知道如何在我看来绑定它。这是我第一次使用标记助手,我确信我的语法不正确

<div class="form-group">
    <label asp-for="Industry.Name" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <select asp-for="Industry.ID" asp-items="ViewBag.Industries" class="form-control"></select>
    </div>
</div>

调用编辑函数时,我没有收到错误,但下拉列表中没有填充任何内容

有人能指出我哪里出了问题吗?

据我所知(尽管我不确定),你应该把asp items=“@ViewBag.Industries”而不是asp items=“ViewBag.Industries”。 我相信你在这里有详细的解释:

选择标记帮助程序需要一个
IEnumerable
重构PopulateIndustriesDropDownList方法以

ViewBag.Industries = new SelectList(industriesQuery, "Industry", "Name", selectedIndustry).Items;

或者在视图中进行演员设置,

谢谢Nemanja,但这仍然不起作用。我一直在进一步阅读,可能我最好有一个ViewModel,而不是将模型直接链接到视图。我要测试一下,看看它是否更适合我的需要。