【问题标题】:MVC SelectList combining multiple columns in text fieldMVC SelectList 在文本字段中组合多列
【发布时间】:2012-09-25 11:46:01
【问题描述】:

我将如何生成一个选择列表,其中文本字段由两个或多个文本列组成,例如:我的数据库中有一个 Description 和 Rate 字段,我想将它们组合起来显示:

Large--£200
Medium--£150
Small--£100

控制器代码是:

 var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
 ViewBag.StandID = new SelectList(stands,"StandID", "Description" + "-- £" + "Rate");

...我的观点是(目前):

    <div class="editor-field"> 
        @Html.DropDownList("StandID", "--Select--") 
    </div> 

...但是“描述”+“-- £”+“价格”);不会运行:

数据绑定: 'System.Data.Entity.DynamicProxies.Stand_63F8C9F623B3C0E57D3008A57081AFCD9C39E1A6B79B0380B60840F1EFAE9DB4' 不包含名称为“Description--£Rate”的属性。

感谢您的帮助,

标记

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    您可以使用简单的 LINQ 投影创建一个新的匿名类,然后使用 SelectList(IEnumerable, string, string) constructor overload 指定要用于 &lt;option&gt; 元素的值和文本字段,即:

    var stands = 
      db.Stands
        .Where(s => s.ExhibitorID == null)
        .Select(s => new 
         { 
           StandID = s.StandID,
           Description = string.Format("{0}-- £{1}", s.Description, s.Rate) 
         })
        .ToList();
    
    ViewBag.StandID = new SelectList(stands, "StandID", "Description")
    

    编辑

    在 C#6 及更高版本中,string interpolationstring.Format 更易于阅读

       ...
       Description = $"{s.Description}-- £{s.Rate}"
    

    如果您投影到强 ViewModel 类名(而不是匿名类),您无疑会希望用 nameof 运算符的安全性替换魔术字符串:

    ViewBag.StandID = new SelectList(stands, nameof(Stand.StandID), nameof(Stand.Description));
    

    【讨论】:

    • 在匿名类型上使用nameof 需要额外的工作,尤其是在可枚举的元素为零的情况下。 This question 可能会有所帮助,特别是 Marc 的回答 stands.GetType().GetTypeInfo().GenericTypeArguments[0];
    • 在 API 连接的情况下我们将如何做到这一点?我得到了这段代码,我在其中检索数据response.Content.ReadAsAsync&lt;IEnumerable&lt;someModel&gt;&gt;().Result;
    【解决方案2】:
    var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
    IEnumerable<SelectListItem> selectList = from s in stands
                                             select new SelectListItem
                                                        {
                                                          Value = s.StandID,
                                                          Text = s.Description + "-- £" + s.Rate.ToString()
                                                        };
    ViewBag.StandID = new SelectList(selectList, "Value", "Text");
    

    【讨论】:

      【解决方案3】:

      您可以创建部分模型类

      public partial class Stand
      {
          public string DisplayName
          {
              get
              {
                  return this.Description + "-- £" + this.Rate.ToString();
              }
          }
      
      }
      

      然后在你的视野中

      var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
      ViewBag.StandID = new SelectList(stands,"StandID", "DisplayName");
      

      【讨论】:

      • 这是迄今为止对我最有帮助的答案!无需摆弄可枚举等,只需使用部分对“主”类进行简单扩展,您就可以开始了。 :)
      【解决方案4】:

      您使用的构造函数的格式是 SelectList(IEnumerable items, string dataValueField, string dataTextField)。

      因此,当您按照自己的方式使用它时,实际上是在告诉它绑定到名为“Description-- £Rate”的文本字段,如果这不是从数据库中传入的字段,则不会知道你在暗示什么。

      只要您在 dataValueField 中的值与您放入该值的属性的名称匹配,并且 dataTextField 与您放置文本的位置的属性名称匹配,上述两种方法中的任何一种都可以使用,也许是混合以上两种解决方案。 (只是因为我更喜欢 lambda 表达式而不是 linq。)并且使用选择列表项可以防止它在转换后对集合执行 ToList。您实际上是在创建自然绑定到选择列表的对象。

      在将它们放入列表之前,您可能还需要检查描述或价格以确保它们不为空

      var stands = db.Stands.Where(s => s.ExhibitorID == null)
                        .Select(s => new SelectListItem
                      {
                          Value = s.StandID.ToString(),
                          Text = s.Description + "-- £" + s.Rate.ToString()
                      });
      
      
      ViewBag.StandID = new SelectList(stands, "Value", "Text");
      

      【讨论】:

      【解决方案5】:

      我通过修改我的视图模型来做到这一点,这是我的代码:

      视图模型

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using MvcEsosNew.Models;
      using System.Web.Mvc;
      
      namespace MvcEsosNew.ViewModels
      {
          public class EntitlementViewModel
          {
              public int EntitlementCount { get; set; }
              public Entitlement Entitlement { get; set; }
              public SelectList Member { get; set; }
              public SelectList Job_Grade { get; set; }
              public SelectList Department { get; set; }
              public SelectList Esos_Batch { get; set; }
          }
      
          public class department_FullName
          {
              public int deptID { get; set; }
              public string deptCode { get; set; }
              public string deptName { get; set; }
              public string fullName { get { return deptCode + " - " + deptName; } }
          }
      }
      

      控制器

      public void getAllDepartment(EntitlementViewModel entitlementVM)
              {
                  var department = from Department in db.Departments.Where(D => D.Status == "ACTIVE").ToList()
                                   select new department_FullName
                                   {
                                       deptID   = Department.id,
                                       deptCode = Department.department_code,
                                       deptName = Department.department_name
                                   };
                  entitlementVM.Department = new SelectList(department, "deptID", "fullName");
              }
      

      观点

           <div class="form-group row">
                      <div class="col-sm-2">
                          @Html.LabelFor(model => model.Entitlement.department_id)
                      </div>
                      <div class="col-sm-10">
                           @Html.DropDownListFor(model => model.Entitlement.department_id, Model.Department, new { @class="form-control" })
                           @Html.ValidationMessageFor(model => model.Entitlement.department_id)
                      </div>
                  </div>
      

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 2010-10-10
        相关资源
        最近更新 更多