【问题标题】:ASP.NET MVC Display HTML Based on User RoleASP.NET MVC 根据用户角色显示 HTML
【发布时间】:2018-10-12 01:29:00
【问题描述】:

遵循最佳实践,是否有更好的方法根据用户的角色显示/隐藏控件,或者在视图中使用 User.IsInRole() 是否完全可以接受? this post 上的回答说它违反了关注点分离。有哪些替代方案?

@if(User.IsInRole("Admin"))
{
    @Html.ActionLink("Create", "Create", "Games")
}

<table class="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col">Date</th>
            <th scope="col">Home</th>
            <th scope="col">Away</th>
            <th scope="col">Field</th>
            <th scope="col">Result</th>
            @if (User.IsInRole("Admin"))
            {
                <th scope="col"></th>
            }
        </tr>
    </thead>
    <tbody>
        @foreach (var g in Model)
        {
        <tr>
            <th>@g.GameDate</th>
            <th>@g.HomeTeam.TeamName</th>
            <th>@g.AwayTeam.TeamName</th>
            <th><a href="http://maps.google.com/?q=directions to @g.Ballpark.Street @g.Ballpark.City @g.Ballpark.StateId" target="_blank">@g.Ballpark.Name</a></th>
            <th>(@g.HomeTeamRuns-@g.AwayTeamRuns) @g.Result</th>
            @if (User.IsInRole("Admin"))
            {
                <th> @Html.ActionLink("Edit", "Edit", new { id = g.GameId })</th>
            }
        </tr>
        }
    </tbody>
</table>

【问题讨论】:

  • 如果我是你,我会为用户和管理员创建单独的视图,因为这是 SOLID 原则中的一个原则,只是为了减少项目中的 if 语句以及如果想对管理员进行更改或用户只有这样这对你才有意义,希望我能帮助你。

标签: c# asp.net asp.net-mvc razor


【解决方案1】:

就个人而言,我会在模型IsAdmin 中添加一个布尔属性,并在控制器中设置值。这样一来,您的视图只能与模型一起使用。

@if (Model.IsAdmin)
{
    // render admin elements
}

【讨论】:

  • 所以代码基本上保持不变,但不是调用 User.IsInRole(),而是检查模型的 Model.IsAdmin 属性?
  • 是的。看起来您当前的模型是某种列表。将此移动到一个单独的模型类中,您可以在其中添加其他属性,例如“IsAdmin”。
猜你喜欢
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2014-08-19
  • 2019-02-12
  • 1970-01-01
相关资源
最近更新 更多