I'm trying to bind UI controls to a business object exposed as a property on an ASP.NET page in a null-safe manner.
Using the 'If' operator is null-safe, but results in compiler error:
Compiler Error Message: BC30201: Expression expected.
Using 'IIf' succeeds, but isn't null-safe. I've tried both the render expression syntax ('<%= %>') binding expression syntax ('<%# %>'), but there was no difference.
Can someone explain this inconsistency and perhaps provide an alternative?
Sample code:
This works: <%=IIf(Me.Foo Is Nothing, "", Me.Foo.Id)%>
This throws the compiler error: <%=If(Me.Foo Is Nothing, "", Me.Foo.Id)%>
Okay, revisiting the question, I think we may be barking up the wrong tree with IF(). The answer probably lies in the error message:
Compiler Error Message: BC30201: Expression expected.
So, I built a sample app. Standard Visual Studio 2008 Web application. I created a class named Bar and added it to my app_code folder:
Imports Microsoft.VisualBasic
Public Class Bar
Public Id As String
End Class
In the default.aspx page, I added the following to the code-behind file:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Foo As New Bar()
End Class
Note that Foo is marked protected.
In the page, I added the following code:
<form id="form1" runat="server">
<div>
<%=If(Me.Foo Is Nothing, "", Me.Foo.Id)%>
</div>
</form>
This works for me, and I get no errors whatsoever. If I then modify the code-behind as follows, I get the expected output ("Something" appears on a blank page):
Partial Class _Default
Inherits System.Web.UI.Page
Protected Foo As New Bar()
Public Sub New()
Foo.Id = "Something"
End Sub
End Class
If this isn't working for you, then my suggestion to you is to verify that you are targeting the .NET 3.5 Framework. When I target .NET 2.0, I get "Expression Expected" on the IF() call. This error does not occur when targeting 3.5.
You can verify that you are targeting 3.5 through the Build tab on the properties for your Web application.
Are you using VB2008? The If() operator was not available in earlier versions of VB, which might explain your compiler error.
In earlier versions of VB, I would use Jason's answer.
<% if someCondition then %>
some html here
<% end if %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With