unpacking viewdata in foreach statement
So I packed some query results in a viewdata statement.
I can verify the correct number of results are put into the viewdata object in the view with this directive:
@foreach (var action in (List<LemonadeTrader.Models.Message>)ViewDa开发者_StackOverflow中文版ta["messages"]) {
When I try to display the results:
@Html.DisplayFor( (LemonTrader.Models.Message)action.msg) // action.msg should be of type string
It says it couldn't convert string to LemonTrader.Models.Lemon.
When I cast it as:
@Html.DisplayFor( (string)action.acidity)
It says:
The type arguments for method 'System.Web.Mvc.Html.DisplayExtensions.DisplayFor(System.Web.Mvc. HtmlHelper, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Not casting it at all doesn't work either.
How do I cast the result?
DisplayFor/EditorFor
works with strongly typed views and view models. It takes as first argument a lambda expression which represents the property on your view model you are trying to display/edit. So throw this ViewData
into the dustbin (which is where it belongs) and use view models and strongly typed views.
So instead of the following horror:
@foreach (var action in (List<LemonadeTrader.Models.Message>)ViewData["messages"]) {
You will have a view model with a Messages property of the correct type:
@foreach (var action in Model.Messages) {
Or even better (why writing foreach
loops when dislpay/editor templates already do this):
@Html.DisplayFor(x => x.Messages)
This way you get many bonuses:
- your code will work
- you get intellisense
- no more brittle magic strings
- instead of resembling to some spaghetti code your views become far more readable
- ...
I think this is just a syntax error, because the DisplayFor expects a Func that gets your model as input.
Try this: @Html.DisplayFor(m => (string)action.acidity)
This worked:
@foreach (var action in (List<LemonTrader.Models.Message>)ViewData["lemons"]) {
<tr>
<td>
@Html.Encode( action.acidity)
精彩评论