MVC table rows visible to matching users only
I'm fairly new to MVC. I'm trying to work ou how to show some data in a table row based on who is logged in. ie. If the person logged in matches the checker for the row then display some content. If there isn't a match show some different content.
I came up with:
<td rowspan="2">
<span>Checker:</span>
@if(item.Checker.Username == HttpContext.Current.User.Identity.Name) {
<div> Show content if logged in user matches row owner </div>
}
else {
<div> Show different content when there isn't a match </div>
}
</td>
I'm wanting to know if this is the correct approach. I understand you're wanting to keep as much logic out of the view as possible so maybe this isn't the best approach.
Can someone please tell me is this an acceptable way of achieving this?
Is ther开发者_开发知识库e a better way?
Actually a better approach would be to add a boolean property on your view model so that your view looks like this:
@if (item.IsCurrentUserOwner) {
<div> Show content if logged in user matches row owner </div>
}
else {
<div> Show different content when there isn't a match </div>
}
Now when the controller maps from the domain model to your view model it will populate this property based on the currently logged in user. Remember that views should be as dumb as possible and authorization logic like this would be better suited to the controller.
If you don't want to bother with this property your approach is also fine. I just gave my 2¢ for improvement.
精彩评论