tags:

views:

21

answers:

1

The TempData output is plain text and putting a div around it will leave a formatted but empty div on the screen if there is no TempData.

Is there a way to apply a class to it so that it only shows when the TempData item is set?

Other than writing the div code into the TempData, which seems like a horrible idea.

+2  A: 

I would probably write a helper:

public static class HtmlExtensions
{
    public static string Message(this HtmlHelper htmlHelper, string key)
    {
        var message = htmlHelper.ViewContext.TempData[key] as string;
        if (string.IsNullOrEmpty(message))
        {
            return string.Empty;
        }
        var builder = new TagBuilder("div");
        builder.SetInnerText(message);
        return builder.ToString();
    }
}

Which could be used like so:

<%= Html.Message("someKeyToLookInTempData") %>
Darin Dimitrov
Good thinking. I will mark this as the answer if no one comes forward with a native solution - cheers.
Pete
One suggestion: return TagBuilder instead of string. That way you could do Html.Message("key").AddCssClass("message") or whatever. Basically you can continue to edit the tag before it's ToString()'d.
Ryan