Reputation: 2609
I'm having a problem where my dynamically generated html is getting escaped and outputed on the screen. heres what I have:
@{
string TrialMessage = string.Empty;
if ((bool)ViewBag.msd.IsOnTrial == true)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var daysToTrialExpiation = expDate.AddDays(1) - System.DateTime.UtcNow;
TrialMessage = "<b>Trial Ends in: <span style=\"color:[Color];\">" + (daysToTrialExpiation.Days) + "</span> Days</b>";
if (daysToTrialExpiation.Days > 5)
{
TrialMessage = TrialMessage.Replace("[Color]", "green");
}
else if (daysToTrialExpiation.Days > 2)
{
TrialMessage = TrialMessage.Replace("[Color]", "orange");
}
else if (daysToTrialExpiation.Days > 0)
{
TrialMessage = TrialMessage.Replace("[Color]", "red");
}
else
{
TrialMessage = "<b style=\"color: red;\"> Trial Ended " + Math.Abs(daysToTrialExpiation.Days) + " Days Ago</b>";
}
}
}
When I use the TrialMessage in the View, I'm getting the escaped version of it outputted on the screen:
<b>Trial Ends in: <span style="color:green;">15</span> Days</b>
I have tried to use Html.Raw(TrialMessage)
I've even tried to manually create an HTMLString
with the same result. What am I missing?
Update: The way I'm outputting it on the view is:
@Html.Raw(TrialMessage)
Upvotes: 0
Views: 729
Reputation: 11796
In an effort to just get it working (it seems you're pressed for time) what if you removed html from the variable?
Perhaps something like this could work for you:
@{
string trialColor = string.Empty;
int trialDays = 0;
if ((bool)ViewBag.msd.IsOnTrial)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var trialDays = (expDate.AddDays(1) - System.DateTime.UtcNow).Days;
if (trialDays > 5)
{
trialColor = "green";
}
else if (trialDays > 2)
{
trialColor = "orange";
}
else
{
trialColor = "red";
}
}
}
...
@if((bool)ViewBag.msd.IsOnTrial && trialDays > 0)
{
<strong>Trial Ends in: <span style="color:@trialColor;">@trialDays </span> Days</strong>
} else if((bool)ViewBag.msd.IsOnTrial) {
<strong style="color: red;">Trial Ended @Math.Abs(trialDays) Days Ago</strong>
}
Note: untested code. It's been a bit since I've written razor.
Upvotes: 2