Search code examples
htmlasp.net-mvcfor-looprazorumbraco

Render <li> tags if string is not null or not empty with Razor


I want to display some li tags only if the strings received from the model contains text. Right now my list looks like this:

ul class="ul-with-bullets">
                @{
                    for (int i = 1; i < 6; i++)
                    {
                        if (@Model.GetValue("punkt" + i) != "")
                        {
                            <li>@Model.GetValue("punkt" + i)</li>
                        }
                    }
                }
</ul>

The Model contains 5 properties (punkt1, punkt2, etc.), and I only want to display a li tag for these that contain a value (string). My above code still displays all the li tags on the page. I tried using string.Empty instead of "" as well but with the same result.

For reference, this is a partial view for the Archetype property editor in Umbraco. Each property in the fieldset is a textstring.


Solution

  • Use the String.IsNullOrEmpty() method

    <ul class="ul-with-bullets">
         @{
            for (int i = 1; i < 6; i++)
            {
               if (!String.IsNullOrEmpty( @Model.GetValue("punkt" + i)))
               {
                  <li>@Model.GetValue("punkt" + i)</li>
               }
            }
          }
    </ul>