views:

87

answers:

2

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>
<% } %>
+1  A: 

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.

Evgeny
+3  A: 

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.

Darin Dimitrov
Darin,I like this approach as it would be very 'easy' to always add the <%= Html.GetMessage() %> to any views by default and just 'forget' about it. then the controller logic could decide whether to add anything into the ViewData["message"]. now, if only there was a way to easily define the key for the viewdata (other than 'message'), then this would be a nicely self-contained extensible little helper :)edit - i suppose of course an additional parameter could be added to the helper to define that attribute - or is there a 'better' way??
jim
This looks great, thanks for the example.
RyanW