调用具有参数 lambda 表达式的方法时可以使用命名参数吗?
我正在使用 C# 4 中的命名参数和可选参数。
特别是,我尝试在 ASP.NET MVC 中调用 HtmlHelpers 时使用命名参数,如下所示...
@Html.DropDownList(name: "ItemGroup",
selectList: Model.ItemGroupList,
htmlAttributes: new { style="width:300px;" })
但是如果我想使用强类型怎么办?将 lambda 表达式而不是字符串值作为第一个参数的助手?
@Html.DropDownListFor(expression: m => m.ItemGroup,
selectList: Model.ItemGroupList,
htmlAttributes: new { style = "width:300px;" })
上面的代码指示了“类型参数...无法从用法推断”的错误。
巧合的是,这工作得很好......
@Html.DropDownListFor(m => m.ItemGroup,
selectList: Model.ItemGroupList,
htmlAttributes: new { style = "width:300px;" })
这可能是非常明显的事情,但当我搜索它时,我很难找到任何可以很好解释它的东西。我可能没有在寻找正确的术语或其他东西。无论如何,我可以朝正确的方向推动。
I'm playing around with named arguments and optional parameters in C# 4.
In particular, I'm trying to use named arguments when calling the HtmlHelpers in ASP.NET MVC like so...
@Html.DropDownList(name: "ItemGroup",
selectList: Model.ItemGroupList,
htmlAttributes: new { style="width:300px;" })
But what if I want to use the strongly typed helpers that take a lambda expression as their first parameter instead of a string value?
@Html.DropDownListFor(expression: m => m.ItemGroup,
selectList: Model.ItemGroupList,
htmlAttributes: new { style = "width:300px;" })
The above code indicates an error along the lines of "the type arguments...cannot be inferred from the usage."
Coincidentally, this works just fine...
@Html.DropDownListFor(m => m.ItemGroup,
selectList: Model.ItemGroupList,
htmlAttributes: new { style = "width:300px;" })
This is probably something really obvious but I'm having difficulty finding anything that explains it well when I search for it. I'm probably not searching for the right terms or something. Anyway, I could use a nudge in the right direction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关于您的“类型参数...无法从用法推断”错误,我只能在发送到 selectList 参数的对象是 List 而不是 SelectList 时才能得到。这对我来说渲染正确:
这会导致页面计时并且从不渲染:
关于为什么为 lambda 表达式指定“表达式:”会导致页面挂起,我不确定。这绝对不是因为它不是可选参数,因为 Url.Action(actionName:"MyPage", controllerName: "MyController") 渲染得很好。看起来只有 lambda 表达式会导致这种行为。
Regarding your "the type arguments...cannot be inferred from the usage" error, I was only able to get that when the object sent to the selectList argument was a List instead of a SelectList. This rendered correctly for me:
This causes the page to clock and never render:
Regarding why specifying "expression:" for a lambda expression would cause the page to hang, I'm not sure. It definitely isn't because it is not an optional parameter because Url.Action(actionName:"MyPage", controllerName: "MyController") renders fine. It looks like just lambda expressions cause this behavior.