Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC LabelFor to replace underscores with CamelCase

my DB model has the column name with "_" in the field name. is there a way to dislay these values in Camel Case when displaying in the form? like "BusinessName"

i am using asp.net MVC3 with Razor

@Html.LabelFor(model => model.business_name)
like image 545
Natasha Thapa Avatar asked Dec 22 '22 11:12

Natasha Thapa


2 Answers

Could you not just use the DisplayAttribute?

like image 190
Jason.Net Avatar answered Dec 24 '22 03:12

Jason.Net


You need a new metadataprovider which can inherit from the default one like this:

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 ...;
    }
}

Register it in global.asax like this:

ModelMetadataProviders.Current = new MyMetadataProvider();

You just need to provide the implementation of GetDisplayNameFromDBName to provide the correct display name given the property name

like image 31
Martin Booth Avatar answered Dec 24 '22 02:12

Martin Booth