I'm ramping up on ASP.NET MVC and looking at how I output messages in the view. What's the best way to do something like this? Helpers? Controls? Or just as is?
<% if (ViewData.ContainsKey("message") && !string.IsNullOrEmpty(ViewData["message"].ToString())) { %>
    <div class="notice">
        <%= ViewData["message"] %>
    </div>
<% } %>
                I would use an html helper:
public static class HtmlExtensions
{
    public static string GetMessage(this HtmlHelper htmlHelper)
    {
        var message = htmlHelper.ViewData["message"] as string;
        if (string.IsNullOrEmpty(message))
        {
            return string.Empty;
        }
        var builder = new TagBuilder("div");
        builder.AddCssClass("notice");
        builder.SetInnerText(message);
        return builder.ToString();
    }
}
and in the view:
<%= Html.GetMessage() %>
Remark: don't forget to html encode the value of the message if you decide to use your code the way it is.
I think a condition like what you have is the simplest approach. A control feels a bit too "heavy" for this. Maybe a helper method if you find yourself repeating it a lot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With