【问题标题】:MVC6 Select Tag Helper & Navigation PropertyMVC6 选择标签助手和导航属性
【发布时间】:2016-04-02 07:39:54
【问题描述】:

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

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);
}

一切似乎都正常,但我不知道如何在我看来绑定它。这是我第一次使用 Tag Helpers,我确信我的语法不正确。

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

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

谁能指出我哪里出错了?

【问题讨论】:

    标签: c# asp.net-core-mvc tag-helpers


    【解决方案1】:

    据我所知(虽然我不确定)你应该使用 asp-items="@ViewBag.Industries" 而不是 asp-items="ViewBag.Industries"。 我相信你在这里有详细的解释: Select Tag Helper in ASP.NET Core MVC

    【讨论】:

    • 感谢 Nemanja 但这仍然没有用。我一直在进一步阅读,可能我最好拥有一个 ViewModel,而不是将 Model 直接链接到 View。我将对此进行测试,看看它是否更符合我的需求。
    【解决方案2】:

    我认为选择标签助手需要IEnumerable&lt;SelectListItem&gt; 将您的 PopulateIndustriesDropDownList 方法重构为

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

    或者在视图中做演员,

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 2019-07-27
      • 2019-05-22
      相关资源
      最近更新 更多