1

I can display a link from a field but I only want to display the link if it's been filled out by the user. I tried surrounding by a conditional statement and checking for the field being null, but even when I don't have the field populated it comes back as true. Here's the code:

@using Sitecore.Mvc
@using Sitecore.Mvc.Presentation

@model Sitecore.Data.Items.Item
@if (Html.Sitecore().Field("External Link", Model) != null)
        {
            @Html.Sitecore().Field("External Link", Model, new { text = @Html.Sitecore().Field("Title", Model) })

        }
3

I don't remember the details, but it looks like Html.Sitecore().Field() returns HTML, which is not what you want to test. Get the actual Item and test item.Fields[ "External Link" ] or item[ "External Link" ]; as Dan Sinclair says, the latter will never actually be null.

| improve this answer | |
  • Yes, I was able to get this working by just referring directly to the field rather than using the Sitecore helper function, thanks! – Levi Wallach Feb 19 '19 at 21:10
0

Sitecore won't return null when you get a field value. Instead, check for an empty string:

@if (!string.IsNullOrEmpty(Html.Sitecore().Field("External Link", Model)))
{
    @Html.Sitecore().Field("External Link", Model, new { text = @Html.Sitecore().Field("Title", Model) })
}
| improve this answer | |
  • Yeah, I tried something like this already, but it didn't work. Intellisense says that it can't convert from system.web.htmlstring to string and there's a runtime error ( CS1502: The best overloaded method match for 'string.IsNullOrEmpty(string)' has some invalid arguments). Even if I tack on a toString(), it returns true (that the string is empty) regardless of whether there's a link or not. – Levi Wallach Feb 18 '19 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.