Is it possible to set authorization on a specific field in MVC 3?
My initial thought (and MSDN research) indicates that the [Authorize] tag is only for controller level actions (create,edit,index,etc). I can do this on the controller action:
[Authorize(Roles = "RoleA,RoleB")]
public ActionResult Create()
{
return View(new Tracking());
}
The scenario is that two roles (RoleA and RoleB) can access the 'Edit' controller. But only RoleA can change the first field. The other role (B) can only view the field.
I would like to do something like this on a specific field:
[Required]
[Range(1, 99)]
[Authorize(Roles = "RoleA")]
public int Sequence { get; set; }
UPDATE1:
A little more research down the StackOverflow rabbit roles reveals that I need to use partial views.
So in my view I add this code:
<div>
@if (Context.User.IsInRole("RoleA"))
{
@Html.Partial("_SequenceEdit")
}
else
{
@Html.Partial("_SequenceView")
}
</div>
So if the user is RoleA they get a partial view that allows editing of the 'sequence' field. Otherwise they get a view only of the 'sequence' field.
My view only partial view looks like this:
<div class="editor-label">
@Html.LabelFor(model => model.Sequence)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.Sequence)
@Html.HiddenFor(model => model.Sequence)
@Html.ValidationMessageFor(model => model.Sequence)
</div>
RoleA? Also how do you know that the user actually changed the value? Change compared to what? - Darin Dimitrov