Why does a lamba-expression work, but when accesing the Model object directly it doesn't?
Here's the error I get:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0411: The type arguments for method 'System.Web.Mvc.开发者_StackOverflowHtml.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Country, ViewData["Countries"] as SelectList) %>
<%: Html.DropDownListFor(Model.Country, ViewData["Countries"] as SelectList) %>
<%: Html.ValidationMessageFor(model => model.Country) %>
</div>
The first DropDownListFor works great; the second gives me the exception. I'm curious as to why this is caused. If I type in Model directly, I still get a list of it's attributed. Why would this break?
Thanks for the help!
The DropDownListFor expects a lambda expression (Actually an Expression<Func<TModel, TProperty>>
). Model.Country is neither an expression nor a function so it won't work there.
Check MSDN SelectExtensions.DropDownListFor
It has to do with the method signature of the helper method. Its for generic dynamic evaluation of the object.
You could write your own overload to the helper that takes only the feature you want.
On a very similar note, I had this issue with MVC3/Razor because I was looping through a model's collection in the HTML. I was trying to use the loop variable and I got this error. In my case, the solution was to go back to the model, using the loop variable in my LINQ query.
My loop:
@foreach (BookField bookField in Model.BookFields)
Changed the first parm in @Html.DropDownListFor from...
bookField
To...
model => model.BookFields.First(q => q.BookFieldId == bookField.Id).Value
The full statement now looks like this:
@Html.DropDownListFor(model => model.BookFields.First(q => q.BookFieldID == bookField.Id).Value, new SelectList(ViewData[ddlKey] as Dictionary<string, string>, "Key", "Value", bookField.Value), "[select]")
Note, I renamed some stuff arbitrarily for this example, so it may not make much logical sense; I just hope it makes enough syntactical sense to help anyone else with this same issue :)
精彩评论