Update 2
So you want to keep as much logic out of the view as possible, in this case you can just pull the if conditions out of the view and into a HtmlHelper extension method.
public static class HtmlHelperExtensions
{
public static bool IsAdmin(this HtmlHelper htmlHelper)
{
return htmlHelper.ViewContext.HttpContext.Current.User.IsInRole("admin");
}
}
Usage:
@if (Html.IsAdmin()) {
...
}
Update
If what you want to only output something if a user is in a role this sort of helper is completely overkill. You should go for a simple if statement in your view.
@if (HttpContext.Current.User.IsInRole("admin")) {
...
}
Making a custom helper
I posted a blog post about this very topic last year where I opened up the ASP.NET MVC source to see how BeginForm() was put together and made my own. Here are the highlights, this will allow you to wrap a <div> around a block in an MVC view.
public class MvcDiv : IDisposable
{
private bool _disposed;
private readonly FormContext _originalFormContext;
private readonly ViewContext _viewContext;
private readonly TextWriter _writer;
public MvcDiv(ViewContext viewContext)
{
if (viewContext == null)
{
throw new ArgumentNullException("viewContext");
}
_viewContext = viewContext;
_writer = viewContext.Writer;
_originalFormContext = viewContext.FormContext;
viewContext.FormContext = new FormContext();
Begin();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Begin()
{
_writer.Write("<div>");
}
private void End()
{
_writer.Write("</div>");
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
End();
if (_viewContext != null)
{
_viewContext.OutputClientValidation();
_viewContext.FormContext = _originalFormContext;
}
}
}
public void EndForm()
{
Dispose(true);
}
}
Then put this extension method somewhere:
public static class HtmlHelperExtensions
{
public static MvcDiv BeginDiv(this HtmlHelper htmlHelper)
{
return new MvcDiv(htmlHelper.ViewContext);
}
}
Then you can use it like so:
@using (Html.BeginDiv())
{
...
}