3
<span class="text-danger">
@{
    if (Model.uploadErrorMessage != null)
    {
        if (!string.IsNullOrEmpty(Model.uploadErrorMessage))
        {
            Model.uploadErrorMessage;
        }
    }
}
</span>

Given code above, how do I display Model.uploadErrorMessage inside <span> tag?

Currently it give me this error on Model.uploadErrorMessage:

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

3
  • Use <text>Html.Raw(Model.uploadErrorMessage)</text> or just <text>@Model.uploadErrorMessage</text>. Commented Apr 27, 2018 at 9:40
  • <span>@Model.uploadErrorMessage</span> Commented Apr 27, 2018 at 9:41
  • The outer if statement is made redundant by the inner one, and you can remove them both anyway - see my answer. Commented Apr 27, 2018 at 9:45

4 Answers 4

5

Put your span tag inside if statement

@{
    if (Model.uploadErrorMessage != null)
    {
        if (!string.IsNullOrEmpty(Model.uploadErrorMessage))
        {
            <span class="text-danger">@Model.uploadErrorMessage</span>
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

All of those if statements are completely unnecessary anyway, you can simplify the entire thing to this:

<span class="text-danger">@Model.uploadErrorMessage</span>

2 Comments

I may put at least one if that embrace the span and not adding an empty DOM to the page when the message is null or empty:-)
@CodeNotFound Well yes, around the span would be different, but it's possible the empty span is required due to some Javascript thing perhaps.
0

use the "@"-symbol to write your variable value to the view:

for example:

<span>This is the error: @(Model.uploadErrorMessage)</span>

Comments

-1

@Html.Raw(Model.uploadErrorMessage)

you can simply put @Model.uploadErrorMessage

Edit: XSS vulnerability fix, based on @DavidG's comment.

7 Comments

That's a bit dangerous though, would absolutely not recommend doing it that way. See here: stackoverflow.com/questions/11144943/…
thanks @DavidG, would you mind elaborating a bit on That's a bit dangerous
Yes, see the link I gave, and here kevinchalet.com/2018/01/09/…
Well now your answer is the same as the existing one, and the big "edit" banner is not needed.
yeah, that'll help others
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.