User defined helper with the feature @using(Html.MyHelper) possible?

15 views
Skip to first unread message

Wolfram Hubert

unread,
Feb 4, 2011, 4:42:51 AM2/4/11
to Community for ASP.NET MVC
Hello MVC Community,

I have written a helper for debugging (Visualization of the partial
views on the website):

using System.Collections.Specialized;
using System.Configuration;
using System.Text;

namespace System.Web.Mvc
{
public static class DebugHelpers
{
/// <summary>
/// Use Html.BeginDebug(this.TemplateInfo.VirtualPath)
/// Example: Convert VirtualPath to a CSS-class
/// VirtualPath: ~/Views/Products/List.cshtml
/// CSS-class: debug-views-products-list
/// </summary>
public static MvcHtmlString BeginDebug(this HtmlHelper html,
string viewName)
{
StringBuilder result = new StringBuilder();

if(Convert.ToBoolean(ConfigurationManager.AppSettings["debug"]))
{
viewName = viewName.Replace("~/", "").Replace("/",
"-").ToLower();
if(viewName.LastIndexOf('.') > -1)
viewName = viewName.Substring(0,
viewName.LastIndexOf('.'));

result.Append(@"<div class=""debug-" + viewName +
@""">");
}
return MvcHtmlString.Create(result.ToString());
}

public static MvcHtmlString EndDebug(this HtmlHelper html)
{
StringBuilder result = new StringBuilder();
if
(Convert.ToBoolean(ConfigurationManager.AppSettings["debug"]))
result.Append(@"</div>");
return MvcHtmlString.Create(result.ToString());
}

}
}

Example for using my helper in a cshtml file:
@Html.BeginDebug(this.TemplateInfo.VirtualPath)
<h2>MyView</h2>
@Html.EndDebug()

Example for the CSS classes in the Site.css
/* Styles for debugging
-----------------------------------------------------------*/
.debug-views-products-list {background-color: Yellow;}
.debug-views-shared-productsummary {background-color:Fuchsia;}
.debug-views-shared-menu {background-color: Lime;}

My helper worked fine. I see helper (example: @using(Html.BeginForm())
{ // some code }), that add to the final tag automatically. Can I use
this feature in my helper? What do I need in my helper to use this
feature?

Regards

Wolfram Hubert

Stephen Russell

unread,
Feb 12, 2011, 7:16:26 PM2/12/11
to c4...@googlegroups.com
Hi Wolfram

On 4/02/2011 8:42 PM, Wolfram Hubert wrote:
> [...]


>
> My helper worked fine. I see helper (example: @using(Html.BeginForm())
> { // some code }), that add to the final tag automatically. Can I use
> this feature in my helper? What do I need in my helper to use this
> feature?

You need to learn about IDisposable. The using statement calls
IDisposable.Dispose at the end of the statement. Your Dispose method could
then call the EndDebug helper.

Steve.

Reply all
Reply to author
Forward
0 new messages