Hide or Disable MVC3 ActionLinks depending on cell

2019-09-03 10:50发布

问题:

MVC3 has created the following table for me

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Author)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Comment)
    </td>
     <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.UserCommentID }) |
        @Html.ActionLink("Details", "Details", new { id=item.UserCommentID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.UserCommentID })
    </td>
</tr>

}

I am sure everyone has seen this sort of thing a million times before.

Does anyone know if there is any way of hiding or disabling the Actionlinks depending on the item.Author.

(I only want an author be able to Edit or Delete his own comments)

I am thinking that the answer might lie with jQuery but I will be very happy with any solution at all.

Many thanks.

回答1:

Something like this

@if(item.Author == loggedInUserIdOrSomethingYouWantToCompareTo) {
    <text>
    @Html.ActionLink("Edit", "Edit", new { id=item.UserCommentID }) |
    @Html.ActionLink("Details", "Details", new { id=item.UserCommentID }) |
    @Html.ActionLink("Delete", "Delete", new { id=item.UserCommentID })
    </text>
}

obviously you should still check on the controller side to make sure the user has the permissions (it would be easy to "fake" these URLs).



回答2:

In addition to Marek's comments - please check the current user when they post/get your edit page as well to make sure they have permissions to this. I could easily forge a link to access something I should have access to or even change any hidden form values you have to tamper with the model when editing something.