I have a model class that has an AreDuesPaid property that I want only administrators to be able to see and edit.
The class looks something like this:
public class ClubMember
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Last name is required")]
public string LastName { get; set; }
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Authorize(Roles="Administrator")] // error: this can only be used for methods
public bool AreDuesPaid{ get; set; }
}
I thought maybe I could use the Authorize attribute, but the compiler tells me this is only for methods.
So, I’m wondering, how can I limit access to a particular property when using DisplayForModel() and EditorForModel() to auto-scaffold views?
Do I need to create entirely separate views and view models or is there an easier way?
Here is the solution I ended up going with:
ViewModels.ClubMember.EditorModel.ViewModels.ClubMember.AdminEditorModelAdminEditorModela property onEditorModel.EditorModel, the service that gets the model checks the credentials of the logged-in user. If the user is an admin, theAdminEditorModelproperty is populated, otherwise, it gets set to null.EditorForModel()to render theEditorModel, then, if theAdminEditorModelis not null, use EditorFor(model => model.AdminEditorModel) to scaffold the remaining properties. (Note:AdminEditorModelwill not be automatically scaffolded when doingEditorForModel()because the defaultobjecttemplate specifically ignores complex properties.)This took some work to implement, but so far, I’m finding it to be a fairly clean solution. It seems to work well with validation, too.
Update
Based on some of the comment on ebb’s answer (especially Danny’s), I decided to sure things up a little more by using completely separate pages for admins vs. regular users. Each page gets it’s own view model (
EditorModelandAdminEditorModel). This took even more work then my initial solution (I had to add new actions to my controller and add mappings between view models and models, but the end result is yet another level cleaner and definitely more secure.