Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for conditional output in ASP.NET MVC?

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>
<% } %>
like image 526
RyanW Avatar asked May 14 '10 07:05

RyanW


Video Answer


2 Answers

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.

like image 190
Darin Dimitrov Avatar answered Sep 27 '22 16:09

Darin Dimitrov


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.

like image 22
EMP Avatar answered Sep 27 '22 17:09

EMP