MVC LabelFor用CamelCase替换下划线

Nat*_*apa 4 c# asp.net-mvc razor

我的数据库模型在字段名称中的列名称为"_".有没有办法在表单中显示时在Camel Case中显示这些值?喜欢"BusinessName"

我正在使用带有Razor的asp.net MVC3

@Html.LabelFor(model => model.business_name)
Run Code Online (Sandbox Code Playgroud)

小智 5

你能不能只使用DisplayAttribute

  • +1,这是正确的方法.添加到您的答案应该使用视图模型而不是一些EF自动生成的域实体到视图中,您的答案将是完美的.而不是说*你不能只使用......*你应该说*你应该使用......*. (2认同)

Mar*_*oth 5

你需要一个新的metadataprovider,它可以从默认的继承,如下所示:

using System;
using System.Web.Mvc;
using System.Collections.Generic;

public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        if (metadata.DisplayName == null)
            metadata.DisplayName = GetDisplayNameFromDBName(propertyName);

        return metadata;
    }

    private string GetDisplayNameFromDBName(string propertyName)
    {
        return ...;
    }
}
Run Code Online (Sandbox Code Playgroud)

在global.asax中注册它,如下所示:

ModelMetadataProviders.Current = new MyMetadataProvider();
Run Code Online (Sandbox Code Playgroud)

您只需提供GetDisplayNameFromDBName的实现,以便在给定属性名称的情况下提供正确的显示名称