1

I have a requirement like this,

Making fields in model as read or write basing on different roles

Suppose in a model i have 15 fields then

User1 with Role1 can edit {Fields 1 to 5; but can view(read only) Fields 6 to 15 } and

User2 with Role2 can edit {Fields 4 ,5,6; but can view(read only) Fields 1 to 3 , 7 to 15}

I googled a lot but i could not find solution

I found a link http://www.codeproject.com/Tips/403921/Field-Based-Security-in-ASP-NET-MVC-3-for-Differen

but using articles we have to create edit templates for different controls to make it read / write

This is one of major task in the project.

Do you have any solution for this.

Thanks, Vijay

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

I don't know if you ever came up with a solution to this and I'd be curious to hear if you did, but for anyone else that stumbles upon this question what I ended up doing was passing a list of the name of all the fields a user has read only access with the view model, and then in my cshtml page I check if the field is part of that list and disable the input tag based on that.

public class DataFields{
    public string Field1 {get; set;}
    public string Field2 {get; set;}
    public string Field3 {get; set;}
    public string Field4 {get; set;}
    public string Field5 {get; set;}
}

public class DataFieldsViewModel{
    public DataFields DataFields {get; set;}
    public IEnumerable<string> ReadOnlyFields {get; set;}
}

And then on my cshtml page something like this:

@var isField1ReadOnly = Model.ReadOnlyFields.Contains(nameof(Model.DataFields.Field1));
@var isField2ReadOnly = Model.ReadOnlyFields.Contains(nameof(Model.DataFields.Field2));
@var isField3ReadOnly = Model.ReadOnlyFields.Contains(nameof(Model.DataFields.Field3));
@var isField4ReadOnly = Model.ReadOnlyFields.Contains(nameof(Model.DataFields.Field4));
@var isField5ReadOnly = Model.ReadOnlyFields.Contains(nameof(Model.DataFields.Field5));

...

<input asp-is-disabled="@(isField1ReadOnly)" asp-for"Model.DataFields.Field1">
<input asp-is-disabled="@(isField2ReadOnly)" asp-for"Model.DataFields.Field2">

asp-is-disabled is based on something like this: https://stackoverflow.com/a/34868369/4573789

Eltee
  • 87
  • 3