开发者

How do I add a css class to the TempData output?

开发者 https://www.devze.com 2022-12-28 17:19 出处:网络
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.

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 开发者_如何学Goseems like a horrible idea.


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") %>
0

精彩评论

暂无评论...
验证码 换一张
取 消