Search code examples
c#asp.netwebgrid

How Do I Get WebGrid To Display Email Link Only If There's Data In The item.Email Field?


I have a WebGrid and I'm trying to pretty it up a bit by showing a mailto link only if there's some content in the ContactEmail field of my SQL query. If there's nothing in ContactEmail field (i.e. NULL or "") I want it to display nothing at all.

The current version has a bog standard:

locationsGrid.Column("ContactEmail", "Email")

but that just displays whatever is in that field as text. Not very aesthetically pleasing.

If I go for:

locationsGrid.Column("ContactEmail", "Email",  format: @<text><a href="mailto:@item.ContactEmail " target="_top">Email</a></text>)

I get the text "Email" in every row, with those having text in the Email field getting a link (as I want) and those without getting it in plain text (which I definitely don't want).

I've tried:

locationsGrid.Column("ContactEmail", "Email",  format: (item.ContactEmail == null || item.ContactEmail == "" ? "" : @<text><a href="mailto:@item.ContactEmail " target="_top">Email</a></text>))

but I'm getting:

Compiler Error Message: CS0103: The name 'item' does not exist in the current context

Could someone help me to rectify this?


Solution

  • I've found a solution to my question, but taken a lateral approach to how I solved it. Basically, instead of scrabbling around with conditionals and lamdba functions in the format property of the WebGrid.Column I've instead created the HTML from the source SQL query. So, whereas the relevant snip of my initial SELECT query said:

    SELECT ContactEmail FROM Clients
    

    it now says:

    SELECT CASE WHEN LEN(ContactEmail) < 1 THEN '' WHEN ContactEmail is null THEN '' ELSE ('<a href=mailto:' + ContactEmail + ' target=_top>email</a>') END AS EmailAddress FROM Clients
    

    This gives me exactly what I want in terms of output to throw into the WebGrid, except if I simply use:

    locationsGrid.Column("EmailAddress", "Email")
    

    the greater-than and less-than symbols in my SQL output for tags get transposed into the entity_name variants that I suppose is a built-in precaution against SQL injection.

    Dealing with that was easy - I just format the output with Html.Raw, so my WebGrid now reads:

    locationsGrid.Column("EmailAddress", "Email", format: @<text> @Html.Raw(item.EmailAddress)</text> )