I have the following enum
public enum StatusEnum
{
Open= 1,
SemiOpen = 2,
Closed= 3
}
I pass it in my ASP.NET 5 view to my custom HTML Helper
@Html.EnumDropDownListFor(m => m.SwitchStatus, typeof (StatusEnum), "- Please select Item -")
which is a method that uses Generic enum as parameter
public static IHtmlContent EnumDropDownListFor<TModel, TResult, TEnum>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
TEnum enumValue,
string optionLabel)
{
// bunch of logic omitted as not relevant to error
//calling another method passing the TEnum
return null;
}
which works.
However I need to pass the enum type between a number of methods as I need to treat it as an TEnum
and not a Type which typeof
will pass.
From the above I add a where clause to tell the method the TEnum is an enum.
public static IHtmlContent EnumDropDownListFor<TModel, TResult, TEnum>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
TEnum enumValue,
string optionLabel) where TEnum : struct, IConvertible, IFormattable
{
// bunch of logic omitted as not relevant to error
//calling another method passing the TEnum
return null;
}
However then I get a red line in my view under
@Html.EnumDropDownListFor
in Visual Studio
showing the error message
Error CS0453 The type 'Type' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method EnumDropDownListFor
Basically as I understand it I need to pass it a TEnum
and not a Type
However if I remove the typeof
from my line
@Html.EnumDropDownListFor(m => m.SwitchStatus, StatusEnum, "- Please select Item -")
I understandably get
StatusEnum is a type which is not valid in the given context
What I basically want to do is do is call typeof
inside the method like this
public static IHtmlContent EnumDropDownListFor<TModel, TResult, TEnum>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
TEnum enumValue,
string optionLabel) where TEnum : struct, IConvertible, IFormattable
{
Type enumValue2 = typeof(StatusEnum);
// bunch of logic omitted as not relevant to error
//calling another method passing the TEnum
return null;
}
and for that I need the MVC View to look something like
@Html.EnumDropDownListFor(m => m.SwitchStatus, Before_typeof(StatusEnum), "- Please select Item -")
so I am allowed to pass it and do the typeof
in the method.
Is this possible?
Take note: I can get it working with the non generic version
i.e.
public static IHtmlContent EnumDropDownListFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
Type enumValue,
string optionLabel)
{
//logic
return null;
}
which works perfectly
I just wanted to know if the generic version is possible somehow