How to define a fixed value attribute in ASP.Net MVC?

Asked

Viewed 324 times

4

I have a user class that has the attribute permissão, that should always be 1. Where and how would I fix this value? In the folder models, controller or in itself view criminal record?

2 answers

4


In the Model, more specifically in the constructor:

public class Usuario
{
    ...
    public int Permissao { get; set; }

    public Usuario() {
        Permissao = 1;
    }
}

To prevent value modification (read-only property), you can do as follows:

public class Usuario
{
    ...
    public int Permissao { get { return 1; } }
}

To prevent the value from being mapped into the Entity Framework (if using), use [NotMapped]:

public class Usuario
{
    ...
    [NotMapped]
    public int Permissao { get { return 1; } }
}
  • Thank you! I will test it when I get home. I had tried it in the view, but it didn’t work. Can I then tell which validation classes and fixed attributes should be done in the models folder? e.g. A class to validate Cpf

  • Yes, any and all validation information needs to be on Model. Validations must be made or making the class implement IValidatableObject or using validation attributes.

0

I would wear:

public class Usuario
{
...
 public const int Permissao = 1;
}

if it is always just a number with no rules, no validations with nothing, then it makes sense to be a constant and ready :)

  • In the context of MVC, this is outside the standard, as much as it works.

  • yes you’re right, but still I’d prefer it that way, since in an elegant way I wouldn’t put either of the two forms in my domain class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.