MVC5填充来自不同表的下拉列表

时间:2017-02-03 02:02:54

标签: c# asp.net-mvc dropdownlistfor

我的控制器如下

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

我的观点如下

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

这会产生错误

  

(&#39; HtmlHelper&#39;不包含。的定义   &#39; DropDownListFor&#39;和最好的扩展方法重载   &#39; SelectExtensions.DropDownListFor(HtmlHelper,Expression&gt;,   IEnumerable,object)&#39;有一些无效的论点。

ClubID来自Clubs表,我填充的模型来自products表。

有人可以向我发送正确的方向。对MVC来说是新手。

感谢。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

为什么不为View创建一个ViewModel,而不是使用ViewBag,为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" })

答案 2 :(得分:0)

您的视图文件不了解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>
相关问题