Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...