I have an HtmlHelper like this: (simplified for clarity)
public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, object>> expressionId)
{
// do something here
tagBuilder.Append(htmlHelper.HiddenFor(expressionId));
// do something here
}
What happens is that the code works fine when expressionId returns string. But when it returns int, Html.HiddenFor trigger this error:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
I don’t know exactly what the problem is, but I suspect it has something to do with this:
When I inspect expressionId in debug mode, I can see the expression is: m => Convert(m.Id) instead of the expected m => m.Id.
What bugs me is that, MyHelper is receiving the exact same argument type as HiddenFor. So why can’t I repass that argument?
What should I do?
PS
I’m not passing any nullable expression into MyHelper (I’ve seen some other questions in which this was the answer)
The problem is with the cast expression of the non-nullable type.
Try using a strongly typed helper instead of
object: