superartsy
superartsy

Reputation: 489

Problems converting an entity property to HiddenField in MVC

I have a Supplier Entitiy that contains

ID - int
Status - string
Name - string
CreateDate- datetime

I am using the partial class method to create Data Annotations for the above Entity.as described here

[MetadataType(typeof(SupplierMetadata))]
public partial class Supplier
{
    // Note this class has nothing in it.  It's just here to add the class-level attribute.
}

public class SupplierMetadata
{
    // Name the field the same as EF named the property - "FirstName" for example.
    // Also, the type needs to match.  Basically just redeclare it.
    // Note that this is a field.  I think it can be a property too, but fields definitely should work.

    [HiddenInput]
    public Int32 ID;

    [Required]
    [UIHint("StatusList")]
    [Display(Name = "Status")]
    public string Status;

    [Required]
    [Display(Name = "Supplier Name")]
    public string Name;
}

the HiddenInput annotation throws an error saying "Attribute 'HiddenInput' is not valid on this declaration type. It is only valid on 'class, property, indexer' declarations."

Please help

Upvotes: 1

Views: 909

Answers (2)

CD Smith
CD Smith

Reputation: 6607

All of your properties are defined incorrectly as they are missing the get/set accessors. All properties in .NET require getter and/or setter accessors. Change your code to this:

public class SupplierMetadata
{
    [HiddenInput]
    public Int32 ID { get; set; }

    [Required]
    [UIHint("StatusList")]
    [Display(Name = "Status")]
    public string Status { get; set; }

    [Required]
    [Display(Name = "Supplier Name")]
    public string Name { get; set; }
}

Upvotes: 1

StanK
StanK

Reputation: 4770

The error states that that attribute can only be added to 'class, property, or indexer declarations'.

public Int32 ID; is none of these - it is a field.

If you change it to a property

public Int32 ID { get; set; } you will be able to decorate it with that attribute.

Upvotes: 4

Related Questions