2

I'm working on an ASP.NET MVC3 application and I annotated my model with an attribute that specifies what roles can change specific fields for any possible status the model is in. Take this as an example:

public class Model
{
   [RoleLimiter(
     new[]{Role.Admin, Role.BasicUser, Role.Validator}, // for draft
     new[]{Role.Admin, Role.BasicUser, Role.Validator}, // for awaiting validation
     new[]{Role.Admin})]                                // for published etc
   public string Subject {get;set;}
}

It looks a bit messy, sure, but it's very easy to change if needed. Now once I have this, it's easy to check for each field the current status and then get the list of roles that can change it. If the current role isn't in it, I'll add a disabled class to the control.

What I wanted to do next is to make a HtmlHelper extension that has the same syntax as the normal EditorFor (or even a straight-forward TextBoxFor), but does this extra check and automatically adds the attribute behind the scenes, but I'm stuck on getting the field info from the expression, ie:

How do you get from

HtmlHelper.TextBoxWithRoleLimitationsFor(x=>x.Subject);

to the attribute attached to x.Subject?

Blindy
  • 65,249
  • 10
  • 91
  • 131

1 Answers1

2

You fetch the LambdaExpression.Body and check whether it's a MemberExpression. You can then get the Member of the MemberExpression and get the custom attributes from that.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Oh that's what I was missing, didn't know I had to cast the body to a more suited class. Thank you! – Blindy Sep 13 '11 at 15:02
  • @Blindy: Just bear in mind that it *could* be any kind of expression, e.g. `TextBoxWithRoleLimitationsFor(x => 1)` – Jon Skeet Sep 13 '11 at 15:08
  • Yep, I made it revert to the normal `TextBoxFor` in case the cast doesn't work. – Blindy Sep 13 '11 at 15:12