Neil
Neil

Reputation: 11899

Using metadata class to override EF field names in MVC view model not working

I am writing an MVC5/EF6 web site, and I'm trying to keep the separation of data model and view models as complete as possible.

So my EF classes (stored in a separate assembly) looks like this:

public class WorksOrder
{
    [Key]
    public int Id { get; set; }

    public string CreatedById { get; set; }
}

I have a metadata class in my view assembly (where the view controllers live) where I override the display name and add error messages

public class WorksOrder
{
    [Display(Name = "Created by")]
    [Required(ErrorMessage = "created by cannot be blank")]
    public string CreatedById { get; set; }
}

I attach the two classes in my view model with:

TypeDescriptor.AddProviderTransparent(
    new AssociatedMetadataTypeTypeDescriptionProvider(typeof(EF.Models.WorksOrder),
    typeof(ViewMetadata.WorksOrder)), typeof(EF.Models.WorksOrder));

When I display the form, the field label is "CreatedById" rather than the display attribute ("Created by") specified in the metadata class. I know the AddProviderTransparent has worked because if I try to submit a form with the CreatedById field empty, I get the error message ("created by cannot be blank").

Edit: This is the Razor file (I've cleaned out the unimportant stuff (divs etc).

@model App.Models.WorksOrderCreateModel

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.WorksOrder.CreatedById, new { @class = "control-label col-md-3" })
    @Html.TextBoxFor(model => model.WorksOrder.CreatedById, new { @class = "form-control col-md-3" })
    @Html.ValidationMessageFor(model => model.WorksOrder.CreatedById)

Upvotes: 1

Views: 11183

Answers (1)

user3177332
user3177332

Reputation: 81

In MetaData class Create a Partial Class something like this.

[MetadataType(typeof(WorksOrderMetaData))]
public partial class WorksOrder
{
}

public class WorksOrderMetaData
{
    [Display(Name = "Created by")]
    [Required(ErrorMessage = "created by cannot be blank")]
    public string CreatedById { get; set; }
}

This will work

Upvotes: 5

Related Questions