MVC5 从不同的 table 填充下拉列表

MVC5 Populate dropdownlist from a different table

我的控制器如下

 public ActionResult Create()
    {
        ViewBag.ClubList = GetClubs();

        return View();
    }

    public static List<SelectListItem> GetClubs()
    {
        List<SelectListItem> ls = new List<SelectListItem>();
        var club = new ClubsService().RecordView().ToList();
        foreach (var item in club)
        {
            ls.Add(new SelectListItem { Text = item.clubID.Trim(), Value = item.clubID.Trim() });
        }

        return ls;
    }

而我的View如下

  @Html.DropDownListFor(model => model.clubID, ViewBag.ClubList, new { @style = "width:400px; text-align: left", @class = "btn btn-default dropdown-toggle" })

这会产生错误

('HtmlHelper' does not contain a definition for 'DropDownListFor' and the best extension method overload 'SelectExtensions.DropDownListFor(HtmlHelper, Expression>, IEnumerable, object)' has some invalid arguments.

ClubID 来自俱乐部 table,其中我填充的模型来自产品 table。

有人可以给我正确的方向吗? MVC 有点新。

谢谢。

您的视图文件不知道 public static List<SelectListItem> GetClubs()。将您的命名空间添加到视图文件夹根目录中的 web.config 文件:

<pages>
    <namespaces>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Web.WebPages"/>
        <add namespace="System.Web.Helpers"/>
        <!--ADD YOUR NAMESPACE HERE-->
        <add namespace="MyCustomHelpers"/>
    </namespaces>
</pages>

我使用另一种方法来防止循环并获得预期结果

var club = new ClubsService().RecordView().ToList();
ViewBag.ClubList = new SelectList(club, "clubID", "clubID");

第一个 clubID 定义值,第二个 clubID 定义文本,我都使用 clubID 因为在您的示例中您使用了 item.clubID 并且在视图

  @Html.DropDownListFor(model => model.clubID, (SelectList)ViewBag.ClubList,"-- Select Clubs --", new { @style = "width:400px; text-align: left", @class = "btn btn-default dropdown-toggle" })

而不是使用 ViewBag,为什么不为您的视图创建一个 ViewModel 添加一个 属性 到您的 ViewModel,它是一个 selectList

public string ClubID {get; set;}
public SelectList ClubList { get; set; }

您可以添加您的视图将在此模型中使用的所有字段。确保在 ViewModel 构造函数中初始化 SelectList

ClubList = new SelectList();

然后在您的控制器中,创建视图模型的实例,获取数据并将其传递给视图:

public ActionResult Create()
{
    var model = new MyViewModel();
    model.ClubList = GetClubs();

    return View(model);
}

public static SelectList GetClubs()
{

    var club = new ClubsService().RecordView().ToList();
    var ls = new SelectList(club, "clubID", "clubID");
    return ls;
}

在你的视图中,在顶部,你可以说:

@model namespace.Where.ViewModel

那么你可以说:

@Html.DropDownListFor(model => model.clubID, Model.ClubList, "Please Select...", new { @style = "width:400px; text-align: left", @class = "btn btn-default dropdown-toggle" })