[c#] The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

Could someone please clarify something for me. In my ASP.NET MVC 2 app, I've got a BaseViewModel class which includes the following method:

public virtual IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
                        (Expression<Func<TModel, TProperty>> propertyExpression)
{
    return new Dictionary<string, object>();
}

The idea being that each child viewmodel can override this method and provide a suitable set of html attributes, based on some logic, to be rendered in the view:

<%: Html.TextBoxFor(model => model.MyProperty, Model.GetHtmlAttributes
                                                 (model => model.MyProperty)) %>

However when used as in the line above, I get a compilation error when I hit the view:

The type arguments for method '...BaseViewModel.GetHtmlAttributes<TModel,TProperty> Expression<System.Func<TModel,TProperty>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I have to do the following:

<%: Html.TextBoxFor(model => model.MyProperty, Model.GetHtmlAttributes
                             <ChildModel, string>(model => model.MyProperty)) %>

I'm just looking for some clarity as to how it tries to infer the type, it has no problem doing so in the HtmlHelper/TextBoxFor extension method?

Is it because HtmlHelper in the view will automatically be for the same type as is specified in the ViewUserControl at the top of the page, whereas my code can be for any type inheriting from BaseViewModel? Is is possible to write this in such a way that it can infer my model/property types?

This question is related to c# linq generics asp.net-mvc-2 expression

The answer is


I had this same problem, my solution:
In the web.config file :

<compilation debug="true>
had to be changed to
<compilation debug="true" targetFramework="4.0">


I was actually searching for a similar error and Google sent me here to this question. The error was:

The type arguments for method 'IModelExpressionProvider.CreateModelExpression(ViewDataDictionary, Expression>)' cannot be inferred from the usage

I spent maybe 15 minutes trying to figure it out. It was happening inside a Razor .cshtml view file. I had to comment portions of the view code to get to where it was barking since the compiler didn't help much.

<div class="form-group col-2">
    <label asp-for="Organization.Zip"></label>
    <input asp-for="Organization.Zip" class="form-control">
    <span asp-validation-for="Zip" class="color-type-alert"></span>
</div>

Can you spot it? Yeah... I re-checked it maybe twice and didn't get it at first!

See that the ViewModel's property is just Zip when it should be Organization.Zip. That was it.

So re-check your view source code... :-)


In case it helps, I've ran into this problem when passing null into a parameter for a generic TValue, to get around this you have to cast your null values:

(string)null

(int)null

etc.


I know this question already has an accepted answer, but for me, a .NET beginner, there was a simple solution to what I was doing wrong and I thought I'd share.

I had been doing this:

@Html.HiddenFor(Model.Foo.Bar.ID)

What worked for me was changing to this:

@Html.HiddenFor(m => m.Foo.Bar.ID)

(where "m" is an arbitrary string to represent the model object)


This error is also related with a cache issue.

I had the same problem and it was solved just cleaning and building the solution again.


You are referring to the type rather than the instance. Make 'Model' lowercase in the example in your second and fourth code samples.

Model.GetHtmlAttributes

should be

model.GetHtmlAttributes

C# compiler have only lambda

arg => arg.MyProperty

for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to generics

Instantiating a generic type Are these methods thread safe? The given key was not present in the dictionary. Which key? Using Java generics for JPA findAll() query with WHERE clause Using Spring RestTemplate in generic method with generic parameter How to create a generic array? Create a List of primitive int? How to have Java method return generic list of any type? Create a new object from type parameter in generic class What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Examples related to asp.net-mvc-2

Better solution without exluding fields from Binding How to set the value of a hidden field from a controller in mvc Making a Simple Ajax call to controller in asp.net mvc ASP.Net MVC - Read File from HttpPostedFileBase without save Session state can only be used when enableSessionState is set to true either in a configuration Using Tempdata in ASP.NET MVC - Best practice Getting index value on razor foreach Current date and time - Default in MVC razor Url.Action parameters? How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Examples related to expression

How do I remove all non-ASCII characters with regex and Notepad++? SSRS Expression for IF, THEN ELSE Regex to get the words after matching string Regular expression to match a word or its prefix SSIS expression: convert date to string Are complex expressions possible in ng-hide / ng-show? Change some value inside the List<T> XPath - Difference between node() and text() javascript - match string against the array of regular expressions Spring cron expression for every after 30 minutes