【问题标题】:Use strongly typed data rather than a string to bind to a drop down list使用强类型数据而不是字符串绑定到下拉列表
【发布时间】:2009-11-30 15:30:26
【问题描述】:

鉴于以下课程......

namespace IMTool.Data
{
    public partial class AllContracts
    {
        internal class Metadata
        {
            public int ContractId { get; set; }
            [Required]
            public string Name { get; set; }
        }
    }
}

并给出以下内容。

using (var context = new IMToolDataContext())
{
    ddlContracts.DataValueField = "ContractId";
    ddlContracts.DataTextField = "Name";
    ddlContracts.DataSource = context
        .AllContracts
        .OrderBy(o => o.Name);
    ddlContracts.DataBind();
}

如何强输入下拉列表 DataValue 和 DataText 字段?基本上我不想使用字符串,而是使用实体中的列名,我使用的是 LinqToSql(以及 PLinqo,它是一组 codesmith 模板来生成我的数据层) 有人可以帮忙吗?

【问题讨论】:

    标签: c# asp.net linq-to-sql strong-typing plinqo


    【解决方案1】:

    创建一个自定义属性来执行此操作

    internal class Metadata
    {
        [MappingColumn (Type="Key")]
        public int ContractId { get; set; }
        [Required]
        [MappingColumn (Type="Name")]
        public string Name { get; set; }
    }
    

    用这个签名创建两个方法

    string GetKeyColumName(Type type) //will perfom a loop on the type properties custom attribute and return the first with the type Key
    
    string GetNameColumnName(Type type)//will perfom a loop on the type properties custom attribute and return the first with the type Name
    

    并像这样填充您的 ddl:

    using (var context = new IMToolDataContext())
    {
        ddlContracts.DataValueField = GetKeyColumnName(typeof(Metadata));
        ddlContracts.DataTextField = GetNameColumnName(typeof(Metadata));
        ddlContracts.DataSource = context
            .AllContracts
            .OrderBy(o => o.Name);
        ddlContracts.DataBind();
    }
    

    编辑: 我指的列属性是 yourcunstom 属性,而不是来自 Linq 的属性。好吧,我应该叫它 MappingColumn 它可以这样声明:

    public class MappingColumnAttribute : System.Attribute 
    {
    
       public string Type {get;set;}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多