So, I am in a situation, where I need to display a different view based on the “Role” that the authenticated user has.
I’m wondering which approach is best here:
[Authorize(Roles="Admin")]
public ActionResult AdminList(int? divID, int? subDivID)
{
var data = GetListItems(divID.Value, subDivID.Value);
return View(data);
}
[Authorize(Roles = "Consultant")]
public ActionResult ConsultantList(int? divID, int? subDivID)
{
var data = GetListItems(divID.Value, subDivID.Value);
return View(data);
}
or should I do something like this
[Authorize]
public ActionResult List(int? divID, int? subDivID)
{
var data = GetListItems(divID.Value, subDivID.Value);
if(HttpContenxt.User.IsInRole("Admin"))
{ return View("AdminList", data ); }
if(HttpContenxt.User.IsInRole("Consultant"))
{ return View("ConsultantList", data ); }
return View("NotFound");
}
In the case where the action is conceptually the same, but the display is different, I would have one action and return different views depending on your discriminator. I’d go with your second example, slightly modified. Note that there is no need to get the data if the user isn’t in an appropriate role.
You realize, of course, that you have the potential for an unhandled exception when you refer to the Value of a potentially null
Nullable<int>, correct?Also, you could, if doing this frequently, refactor the construction of the view prefix into a common method.
Then call it as