将Viewbag数据与HTMLHelper MVC3一起使用。 - 无法动态调度

时间:2012-01-17 15:15:47

标签: c# asp.net-mvc asp.net-mvc-3 enums

我正在使用以下功能将我的枚举变成radiobuttons

的集合
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression
)
{

但是,这意味着我必须使用类似html.RadioButtonForEnum(a => a.inputEnum)的内容来使用它, - a是我的网页模型。

当我想要执行以下操作时,我的问题就出现了: html.RadioButtonForEnum(Viewbag.inputEnum)

我收到以下错误:

CCS1973: 'System.Web.Mvc.HtmlHelper<MyProject.Models.MyModel>' has no applicable method named 'RadioButtonForEnum' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

我尝试对其应用强制转换,但是如果通过Viewbag传递枚举而不是页面模型,则无法加载它。

2 个答案:

答案 0 :(得分:2)

描述

您可以使用enumType作为参数而不是表达式创建第二个方法。

示例

public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    TypeOfYourEnum value
)

更多信息

答案 1 :(得分:0)

我有两个解决方案,我可以提出:

创建一个接受枚举而不是表达式的函数:

public static MvcHtmlString RadioButtonForEnum(this HtmlHelper htmlHelper, MyEnumType enum)
{
  //Code to generate radio button here
}

选项2是创建局部视图(可能是过度杀戮)。