da_erik da_erik - 1 month ago 9
C# Question

Check length of String passed from Model

I'm working in ASP.NET MVC and I'm having some issues checking, in my view, if a string passed from my Model is empty or not.

I have a

<p>
-tag, inside a
<div>
, like so:

<div class="category-text">
<p class="sidebar-text">@Html.Raw(Model.Text)</p>
</div>


Which in some cases will hold text and in some cases won't, so I want the whole div containing this
<p>
-tag to not display IF the text is empty. I wrote a jQuery function for this:

if ($(".sidebar-text").text().length) {
$(".category-text").show();
}


This function seems to be working. If I for example hardcode "asd" into the
<p>
-tag and log it in the console it gives me "3", which is how I expect it to be working.

My problem is that using
@Html.Raw(Model.Text)
always returns 0, which makes the whole
category-text
div not show. I know for a fact that Model.Text has value, and using
@Html.Raw(Model.Text)
somewhere else in my view proves that text is actually in the
Model.Text
-object.

What am I missing?

Answer Source

Surround the <div> with an if statement, like so:

@if(!String.IsNullOrEmpty(Model.Text))
{
    <div class="category-text">
        <p class="sidebar-text">@Html.Raw(Model.Text)</p>
    </div>
}

This will prevent the whole <div> from rendering to the response it wont be available in the DOM.

If, however, you need the <div> present in the DOM but invisible, due to the empty paragraph, you could set the CSS visibility property on the server. E.g.

<style>
    .invisible { visibility: hidden; }
</style>

Then the HTML for the <div> would look like this:

<div class="category-text @(String.IsNullOrEmpty(Model.Text) ? String.Empty : invisible)">
    <p class="sidebar-text">@Html.Raw(Model.Text)</p>
</div>