How to show frame if validate message for is valid in Razor?

1.8k views Asked by At

I am searching for a while solution, but I can not found it. I have this ValidateMessageFor in my Razor, which show error message if it cames to there.

Now I have create this css frame for this message and I whant to it be displayed only if there is some ValidateMessage.

I have try this:

@{
    if (@Html.ValidationMessageFor(u => u.CustomType) != null)
    {
    <p class="alert alert-danger alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>@Html.Raw(@Html.ValidationMessageFor(u => u.CustomType))
    </p>
    }
}

But this is not working. Problem is that frame is always displayed (inside is no error message, until I make mistake, and then error message displays). This is how it looks, when I come to this form:

enter image description here

If error shows:

enter image description here

1

There are 1 answers

3
AliRıza Adıyahşi On BEST ANSWER

Try this: @Html.Raw(Server.HtmlDecode(@Html.ValidationMessageFor(u => u.CustomType).ToString())))

full code:

@{
    if (!String.IsNullOrEmpty(@Html.ValidationMessageFor(u => u.CustomType).ToString()))
    {
    <p class="alert alert-danger alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert">
            <span aria-hidden="true">&times;</span>
            <span class="sr-only">Close</span>
        </button>
        @Html.Raw(Server.HtmlDecode(@Html.ValidationMessageFor(u => u.CustomType).ToString())))
    </p>
    }
}