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

asp.net-mvc asp.net-mvc-5 c# entity-framework

Question

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)
1
1
2/20/2014 10:51:24 AM

Popular Answer

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

5
3/17/2014 1:53:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow