【问题标题】:Html.DropDownListFor extension method to populate values based on User Role ASP.NET MVC3基于用户角色 ASP.NET MVC3 填充值的 Html.DropDownListFor 扩展方法
【发布时间】:2013-01-18 20:08:34
【问题描述】:

我正在探索与登录用户角色相关的 Asp.net MVC 中的 DropDownBox 的通用解决方案。以下是场景:

如果 UserRole 为 X,则网页 A 上的 DropDown 必须有多个值。

如果 UserRole 为 Y,则网页 A 上的 Dropdown 必须具有单个值,并且下拉列表必须为 ReadONLY,默认为单个值。

值将由控制器通过 ViewBag 提供给视图

有人可以帮我解决这个场景的扩展方法吗?

【问题讨论】:

  • 值将由控制器通过 ViewBag 提供给视图。

标签: asp.net-mvc-3 razor


【解决方案1】:

Here 是下载 MVC3 源代码的链接。您要查找的文件是 mvc3-rtm-sources\mvc3\src\SystemWebMvc\Mvc\Html\SelectExtensions.cs。该文件包含 DropDownList 和 DropDownList 的所有扩展方法。

您要查找的内容类似于以下内容:

[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListForRoles<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, UserRole role, IDictionary<string, object> htmlAttributes) {
    if (role == 'X') {
        //edit the select list as necessary
    }
    else if (role == 'Y') {
        // have the single value
        // add the read-only attribute to htmlAttributes
    }
    return DropDownListHelper(htmlHelper, expression, selectList, htmlAttributes);
}

这至少应该是您正在寻找的一个很好的起点。没有更多细节,我只能真正给你伪代码。但是,您应该能够从那里调整您需要的内容。

不要忘记检查它们对所有功能的不同覆盖。您可能认为现在不需要它们,但很高兴知道所有选项都在那里,以后应该会有所改变。就像他们拥有它们一样,只是让这些方法返回您创建的方法调用带有所有可能参数的方法,并在必要时传递空值。

【讨论】:

  • 太棒了,谢谢你的帮助。感谢您指点我下载 MVC3 源代码。
  • 不客气。当我发现微软提供了它的源代码时,我感到很惊讶。
  • 要指出的另一件事是,如果您是 MVC 新手,请注意 @Html.Label。这与其他 HTML 帮助器方法的行为不同。看看我对here 的问题的回答,关于它发生了什么。我最终为 Span 创建了一系列辅助方法来解决这个问题。
猜你喜欢
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 2021-06-14
  • 2015-07-10
  • 2011-08-11
  • 2012-02-17
相关资源
最近更新 更多