Vadzim Savenok Vadzim Savenok - 3 months ago 7
ASP.NET (C#) Question

Set string to empty if no version number exists in Razor HTML

I am building a simple structure in cshtml: if no version number exists, set string to empty, otherwise place a link with version info

<label style="float:right;">
Version: @resp.VersionNumber
@if (string.IsNullOrEmpty(@resp.VersionNumber))
{
@resp.VersionNumber == "";
}
else
{
<a>Version link code</a>
}
</label>


Resp is JsonResponce local variable, while VersionNumber is a string Datamember of JsonResponce class.

While it looks extremely easy, it was returning errors that made me scratch my head.

The error is inside the if statement. I tried encasing the line in the () like was suggested by accepted answer in that thread, but it was returning a compilation error, like in that post. Structures in both cases are a bit different than mine, so I cannot exactly apply those.

If I leave the line inside if as is, it was returning compilation errors of
invalid expression term ==
and
expected ;
, even though I already have it.

I understand that I am probably missing something simple, but can you please point me to how I should change my code in order to remove those errors. And briefly explain why it is doing this, since I want to learn from this question as well.

I am a beginner self-learner in that area, so please go easy on me. Thank you very much!

UPDATE



Based on everyones's proposed suggestions, I rearranged my code, and now it looks like the following

<label style="float:right;">
Version:
@if (string.IsNullOrEmpty(resp.VersionNumber))
{
<span></span>;
}
else
{
@resp.VersionNumber
<a>Version link code</a>
}
</label>

Answer

You have several errors. First you have @ in places where it doesn't belong, since you're already in a code block. You use comparison (==) when you most likely want assignment(=). You also first output the value and then want to modify it.

Most likely you are after something like this

<label style="float:right;">
  Version:
  @if (string.IsNullOrEmpty(resp.VersionNumber))
  {
    <span>No version number!</span>
  } else {
    <a>Version link code</a>
  }
</label>

This way you check if it exists, if not you just output a text and if it does you do the link how you want.