@Html.DropDownList("DropDownID", Model.Items)
The way I accomplished this was extension methods. Extension methods are an interesting way to add functionality to a class without inheritence. There are drawbacks, such as not being able to access protected members of the base class, but for some cases this is ok.
I decided to use extension methods to add a method to the class that corresponded to the @Html object in the Razor engine. I found out that this class was the HtmlHelper class in the System.Web.Mvc namespace. By extending the HtmlHelper class via extension methods, I was able to achieve my goal of adding a custom widget.
namespace MvcHtml { using System.Web.Mvc; public static class ExtensionHtml { public static MvcHtmlString CustomWidget(this HtmlHelper htmlHelper, string property) { TagBuilder tagBuilder = new TagBuilder("div"); tagBuilder.SetInnerText(property); return new MvcHtmlString(tagBuilder.ToString()); } } }
After this little bit of work, we are ready to use the custom widget in our view template just as traditional widgets provided for us.
@Html.CustomWidget("SampleProperty")
I hope this helps people understand how Razor is producing HTML from these view files!
2 comments:
How about adding content to the widget?
@K siva Karthikeyan
What do you mean by content? You can make the response of the function whatever html you want. You don't even have to use the tag builder if you don't want to.
Post a Comment