Reputation: 33
Many of my HTML helpers get a lambda expression as a parameter. The helpers are called from MVC views, and the lambda expression provides the helper one of the fields from the view's underlying model. The following works fine:
//Helper:
public static MvcHtmlString MyHelper<T, TValue>(this HtmlHelper<T> helper,
Expression<Func<T, TValue>> Parameter1
/*More parameters*/)
//View:
@Html.MyHelper(m => m.Field1 /*More parameters*/)
I would like to add a second parameter that would make a second field from the model available for the helper, something along this line:
//Helper:
public static MvcHtmlString MyHelper<T, TValue>(this HtmlHelper<T> helper,
Expression<Func<T, TValue>> Parameter1,
Expression<Func<T, TValue>> Parameter2
/*More parameters*/)
//View:
@Html.MyHelper(m => m.Field1,
m => m.Field2 /*More parameters*/)
The view generates a CS0411 compilation error (The type arguments for method '...' cannot be inferred from the usage. Try specifying the type arguments explicitly.). I understand the core of the error message, but do not know how to map that to this case.
The following does compile, but I do not know how to get the two parameters at the side of the Helper method:
//View:
@Html.MyHelper(m => new
{
m.Field1,
m.Field2
} /*More parameters*/)
How should I transfer more than one field (column) from the view's underlying model to an HTML helper?
Upvotes: 2
Views: 114
Reputation: 62498
There are two different type parameters involved most probably for both fields i.e. Field1
and Field2
while you are using same TValue
for both.
So when we invoke the helper the types can differ of both Properties.
You will need to introduce a third type parameter in this particular case.
So try like:
public static MvcHtmlString MyHelper<T, TParam1,TParam2>(this HtmlHelper<T> helper,
Expression<Func<T, TParam1>> Parameter1,
Expression<Func<T, TParam2>> Parameter2
/*More parameters*/)
as the type of both properties can differ so a common TValue
parameter wouldn't work.
Upvotes: 3