Html.DropDownListFor基于用户角色ASP.NET MVC3填充值的扩展方法

时间:2013-01-18 20:08:35

标签: asp.net-mvc-3 razor

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

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

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

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

有人可以帮我解决这种情况的扩展方法吗?

1 个答案:

答案 0 :(得分:0)

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

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

[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);
}

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

不要忘记查看它们对所有功能的不同覆盖。你现在可能认为你不需要它们,但是如果知道所有选项都应该在以后发生变化,那么总是很好。那些像他们拥有它们的那些,只是让那些方法返回你创建的方法调用带有所有可能参数的方法,在必要时传入空值。

相关问题