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:
pu
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... :-)
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
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)
In your example, the compiler has no way of knowing what type should TModel
be. You could do something close to what you are probably trying to do with an extension method.
static class ModelExtensions
{
public static IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
(this TModel model, Expression<Func<TModel, TProperty>> propertyExpression)
{
return new Dictionary<string, object>();
}
}
But you wouldn't be able to have anything similar to virtual
, I think.
EDIT:
Actually, you can do virtual
, using self-referential generics:
class ModelBase<TModel>
{
public virtual IDictionary<string, object> GetHtmlAttributes<TProperty>
(Expression<Func<TModel, TProperty>> propertyExpression)
{
return new Dictionary<string, object>();
}
}
class FooModel : ModelBase<FooModel>
{
public override IDictionary<string, object> GetHtmlAttributes<TProperty>
(Expression<Func<FooModel, TProperty>> propertyExpression)
{
return new Dictionary<string, object> { { "foo", "bar" } };
}
}
C# compiler have only lambda
arg => arg.MyProperty
for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.
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.