在 foreach 语句中解压 viewdata
所以我将一些查询结果打包在 viewdata 语句中。
我可以使用以下指令验证将正确数量的结果放入视图中的 viewdata 对象中:
@foreach (var action in (List<LemonadeTrader.Models.Message>)ViewData["messages"]) {
当我尝试显示结果时:
@Html.DisplayFor( (LemonTrader.Models.Message)action.msg) // action.msg should be of type string
它表示无法将字符串转换为 LemonTrader.Models.Lemon。
当我将其投射为:
@Html.DisplayFor( (string)action.acidity)
它说:
方法的类型参数 'System.Web.Mvc.Html.DisplayExtensions.DisplayFor(System.Web.Mvc. Html助手, System.Linq.Expressions.Expression>)' 无法从用法推断。尝试 指定类型参数 明确地。
根本不铸造它也不起作用。
我如何投射结果?
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>)ViewData["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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DisplayFor/EditorFor
适用于强类型视图和视图模型。它采用 lambda 表达式作为第一个参数,该表达式表示您尝试显示/编辑的视图模型上的属性。因此,将这个 ViewData 扔进垃圾箱(这是它所属的地方)并使用视图模型和强类型视图。因此,不要出现以下恐怖情况:
您将拥有一个具有正确类型的 Messages 属性的视图模型:
或者甚至更好(当 dislpay/editor 模板已经这样做时,为什么要编写
foreach
循环):这样您获得很多好处:
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 thisViewData
into the dustbin (which is where it belongs) and use view models and strongly typed views.So instead of the following horror:
You will have a view model with a Messages property of the correct type:
Or even better (why writing
foreach
loops when dislpay/editor templates already do this):This way you get many bonuses:
我认为这只是一个语法错误,因为 DisplayFor 需要一个 Func 来获取您的模型作为输入。
试试这个:@Html.DisplayFor(m => (string)action.acidity)
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: