如何访问System.ComponentModel.DataAnnotations显示名称属性字段 [英] How to access the System.ComponentModel.DataAnnotations Display name property for a field

查看:211
本文介绍了如何访问System.ComponentModel.DataAnnotations显示名称属性字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图模型,其中属性有显示名称。我现在正在制作Excel工作表与在网页网格相同的数据。我使用的关闭XML (至极使用OPENXML)在服务器上创建Excelsheet并将其发送给Web客户端时,他们要下载的数据为Excel。
当我写在Excel中OPENXML流标题行我想重用我已经定义的显示名称。但我不能想出叫什么。
这里是显示名称的一个例子。 (对于这个例子我只用两个,现实中有很多很多的列):

I have a viewmodel where the properties have display names. I am now making a Excel sheet with the same data in as the grid in the webpage. I am using closed xml (wich uses openxml) to create the Excelsheet on the server and send it to the webclient when they want to download data as Excel. When i write the header row in Excel openxml stream I want to reuse the displayname that I already have defined. But I cant figure out what to call on. Here is an example of the display name. ( For the example I only use two, reality there are many many more columns) :

 using System.ComponentModel.DataAnnotations;
 public class DCArrival : IDCArrival
 { 
   [Display(Name = "Via Transit")]
   public String LocationType { get; set; }
   [Display(Name = "Currency")]
   String CurrencyISOCode { get;  }
 }

然后我想,当我创建的标题行使用此显示名称。马克伪code,它tryes解释什么,我想弄个:

Then I want to use this displayname when I create the header row. Mark the pseudocode that tryes to explain what I want to get hold of:

private MemoryStream CreateExcelFile(ICollection<DCArrival> dcArrToShow
, QueryStrInput   queryStrInput)
    {
        try
        {
            // Create an Excel Workbook
            XLWorkbook wb = new XLWorkbook();
            // Add the worksheet with  data 
            IXLWorksheet ws = wb.Worksheets.Add("New Worksheet");
            // Add my data that was displayed in the html table ... 
            ws.Cell(1, 1).SetValue("Hello World");
           //Add Header row. By taking a object in the collection and figure out its
           // display name
           DCArrival firstRow = dcArrToShow.First();
           // Here comes my problem. Here is my dream up mockup code

            ws.Cell(2,1).Value = firstRow.LocationType.DisplayAttribute.GetName()
            ws.Cell(2,2).Value = firstRow.CurrencyISOCode.DisplayAttribute.GetName()
           // back to reality
           //this is how easy I can get all data from Collection
            ws.Cell(3, 1).Value = dcArrToShow.AsEnumerable();
          // All done
            MemoryStream ms = new MemoryStream();
            wb.SaveAs(ms);
            return ms;
        }
        catch (Exception e)
        {
            string errmsg = String.Format("Failed to create Excel file: {0}",
          e.Message);
            throw new Exception(errmsg, e);
        }

我已经看了<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx
但我不明白,我怎么得到它的搁置。
据我所知,这是神奇固定的,当你使用普通的MVC 3 HTML渲染。当我谷歌这些概念,我得到博客淹死谁愿意在MVC 3。

I have looked at the http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx But I do not understand how I get a hold of it. I understand that this is magically fixed for you when you are using normal mvc 3 html rendering. When I Google these concepts I get drowned in blogs who wants to explain basic validation in MVC 3.

推荐答案

您可以从模型元数据检索:

You could retrieve it from the model metadata:

ws.Cell(2.1).Value = ModelMetadata.FromLambdaExpression<DCArrival, string>(x => x.LocationType, new ViewDataDictionary<DCArrival>(firstRow)).DisplayName;

或写一个扩展方法:

public static class ModelMetadataExtensions
{
    public static string GetName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> ex)
    {
        return ModelMetadata
            .FromLambdaExpression<TModel, TProperty>(ex, new ViewDataDictionary<TModel>(model))
            .DisplayName;
    }
}

和则:

ws.Cell(2.1).Value = firstRow.GetName(x => x.LocationType);
ws.Cell(2.2).Value = firstRow.GetName(x => x.CurrencyISOCode);


更新:

根据新的要求,即通过了所有属性在评论部分pssed以循环前$ P $,读取显示属性,你可以使用下列内容:

As per a new requirement that was expressed in the comments section in order to loop through all properties and read the display attribute you could use the following:

var properties = typeof(DCArrival).GetProperties(); 
foreach (var property in properties) 
{
    var displayAttribute = property
        .GetCustomAttributes(typeof(DisplayAttribute), true)
        .FirstOrDefault() as DisplayAttribute;
    string displayName = property.Name;
    if (displayAttribute != null)
    {
        displayName = displayAttribute.Name;
    }

    // TODO: do something with the display name for this property
} 

这篇关于如何访问System.ComponentModel.DataAnnotations显示名称属性字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆