Use Lambda Expression within ASP.NET MVC View using VB.NET
With ASP.NET MVC 1.0, .NET 3.5 and C# you can easily pass a method a lambda expression that will do a "Response.Write" some content when it's executed within the method:
<% Html.SomeExtensionMethod(
() => { <%
<p>Some page content<p>
%> }
) %>
The method signature is similar to this:
public void SomeExtensionMethod(this HtmlHelper helper, A开发者_JS百科ction pageContent)
{
pageContent();
}
Does anyone know how to peforma a similar call using Lambda expressions in VB.NET using the same method signature shown above?
I've tried the following in VB.NET, but it wont work:
<% Html.SomeExtensionMethod(New Action( _
Function() %> <p>Some Content</p> <% _
)) %>
I get an exception saying "Expression Expected."
Can anyone help me with what I'm doing wrong? How do you do this in VB.NET?
VB.NET 9.0 doesn't support multi-statement lambda expressions or anonymous methods. It also does not support lambda expression that does not return a value meaning that you cannot declare an anonymous function of type Action.
Otherwise this works but is meaningless because the lambda does nothing:
<% Html.SomeExtensionMethod(New Action(Function() "<p>Some Content</p>"))%>
Now let's take your example:
<% Html.SomeExtensionMethod(New Action( _
Function() %> <p>Some Content</p> <% _
)) %>
Should be translated to something like this:
Html.SomeExtensionMethod(New Action(Function() Html.ViewContext.HttpContext.Response.Write("<p>Some Content</p>")))
which doesn't compile in VB.NET 9.0 because your expression doesn't return a value.
In VB.NET 10 you will be able to use the Sub keyword:
Html.SomeExtensionMethod(New Action(Sub() Html.ViewContext.HttpContext.Response.Write("<p>Some Content</p>")))
which will compile fine.
精彩评论