【问题标题】:Help with asp.net mvc SelecList, Html.dropdownList and linqtosql帮助 asp.net mvc SelecList、Html.dropdownList 和 linqtosql
【发布时间】:2011-01-09 19:53:47
【问题描述】:

我有 users 表,它有 id,name last name

我有一个 linq to sql 类

我想要一个下拉列表,其中包含 id 值和 NAME 和 LASTNAME 文本......我该怎么做?

ViewData["User_Id"] = new SelectList(UsersRepository.GetAll(), "Id", "Name");

效果很好,但我想要

ViewData["User_Id"] = new SelectList(UsersRepository.GetAll(), "Id", "Name "+" Last_Name");

这不起作用...请帮助

【问题讨论】:

    标签: asp.net-mvc drop-down-menu


    【解决方案1】:

    尝试使用一些好的旧 LINQ。

    var data = from u in UsersRepository.GetAll()
                select new {
                   Id : u.Id,
                   Name : string.Concat(u.Name, u.LastName)
                };
    ViewData["User_Id"] = new SelectList(data, "Id", "Name");
    

    【讨论】:

      【解决方案2】:

      此控件使用反射来查找 dataText 和 dataValue 的正确属性。您将无法将这些属性添加在一起。

      你可以创建一个匿名类型。

      假设数据库中的集合如下所示:

          var testModelCollection = new List<TestModel>() { 
              new TestModel() { Id = 1, Name = "Bob", LastName = "Smith" },
              new TestModel() { Id = 2, Name = "Jack", LastName = "Thompson" }
          };
      
          var changedModelCollection = from t in testModelCollection
                                       select new {
                                           Id = t.Id,
                                           FullName = t.Name + " " + t.LastName
                                       };
      
      
          ViewData["User_Id"] = new SelectList(changedModelCollection, "Id", "FullName");
      

      您在视图中对 DropDownList 的定义如下所示:

      <%= Html.DropDownList("Username", (SelectList)ViewData["User_Id"], "Select a User") %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        • 2011-01-31
        • 2011-08-17
        • 1970-01-01
        • 2014-06-04
        • 2010-10-25
        相关资源
        最近更新 更多