简体   繁体   English

如何从资源文件本地化WebGrid列标题

[英]How to localize WebGrid column headers from resource file

I have localised the display of property names in my applications by adding the Display attribute, which gets the string value from a resx file: 我通过添加Display属性在应用程序中本地化了属性名称的Display ,该属性从resx文件获取字符串值:

public class ViewLeadViewModel
{
    [Required]
    [Display(Name = "Location", ResourceType = typeof(FormLabels))]
    public string Location { get; set; }
}

This works fine in forms and when viewing the data in a basic grid. 在表单中以及在基本网格中查看数据时,这都可以正常工作。

However, I want to use a WebGrid to dispaly the data, but it seems that the Display attribute is not supported, and we can only use DisplayName for this (currently the column headers just use the actual name of the property). 但是,我想使用WebGrid分配数据,但似乎不支持Display属性,因此我们只能为此使用DisplayName (当前列标题仅使用该属性的实际名称)。

I tried adding this attribute: 我尝试添加此属性:

[DisplayName(FormLabels.ResourceManager.GetString("Location"))]

But I get the error 但是我得到了错误

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type 属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式

How can I localise the column headers in WebGrid from a resource file? 如何从资源文件本地化WebGrid的列标题?


Update 更新

Here is the code in Index.cshtml : 这是Index.cshtml的代码:

@model IEnumerable<AuroraWeb.Models.ViewLeadViewModel>

@{ 
    var grid = new WebGrid(new List<object>());

    grid = new WebGrid( Model,
                        rowsPerPage: 100);
}

@grid.GetHtml(
    tableStyle: "table",
    alternatingRowStyle: "alternate")

You can create a custom attribute class inherited from DisplayNameAttribute and set the DisplayName string property inside the attribute by providing the resource key, given by this example below: 您可以创建一个从DisplayNameAttribute继承的自定义属性类,并通过提供资源密钥来设置属性内的DisplayName字符串属性,如以下示例所示:

// provided by Brian Schroer
[AttributeUsage(AttributeTargets.Property)]
public class LocalizedDisplayNameAttribute : DisplayNameAttribute 
{
    public LocalizedDisplayNameAttribute(string resourceKey)
    {
        ResourceKey = resourceKey;
    }

    private string ResourceKey { get; set; }

    public override string DisplayName
    {
        get
        {
            string displayName = FormLabels.ResourceManager.GetString(ResourceKey);
            return string.IsNullOrEmpty(displayName) ? string.Format("[[{0}]]", ResourceKey) : displayName;
        }
    }
}

Example usage: 用法示例:

[LocalizedDisplayName("Location")]
public string Location { get; set; }

Reference: 参考:

ASP.NET MVC localization DisplayNameAttribute alternatives: a good way ASP.NET MVC本地化DisplayNameAttribute替代方法:一种好方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM