首页 > 解决方案 > 选择 Tag Helper 混淆

问题描述

如果我有这个

public class EventListViewModel
{
    public string Id { get; set; }
    public string Description { get; set; }
}

并在控制器中

public IActionResult Index()
{
List<EventListViewModel> eventList = this.eventStructureBLL.EventListGetBy("it");
return View(eventList);
}

并在查看此

@model List<Common.DAL.ViewModels.EventListViewModel>

什么是正确的选择标签助手

<select asp-for="??" asp-items="???"></select>

标签: c#drop-down-menuasp.net-core-tag-helpers

解决方案


选择某些东西并将其发回需要将其绑定到的东西。由于它将是单个项目,因此您需要以下内容:

public class FooViewModel
{
    public int SelectedEventId { get; set; }
}

那么,该属性就是您要绑定的:

<select asp-for="SelectedEventId" ...></select>

然后,您还需要传递您的选项列表,它应该是一个IEnumerable<SelectListItem>. 由于您已经有一个视图模型,因此对于您要绑定的属性,请将其添加为那里的属性:

public class FooViewModel
{
    public int SelectedEventId { get; set; }
    public IEnumerable<SelectListItem> EventOptions { get; set; }
}

要在您的操作中填写此内容:

model.EventOptions = this.eventStructureBLL.EventListGetBy("it").Select(x => new SelectListItem
{
    Value = x.Id.ToString(),
    Text = x.Description
});

然后,当然,这个模型将是你传递给你的视图的东西:

return View(model);

并且,在视图中:

@model FooViewModel

最后,您的选择标签将是:

<select asp-for="SelectedEventId" asp-items="@Model.EventOptions"></select>

推荐阅读