0

I want to create reusable widgets for a web site created with ASP.NET MVC and Razor. Basically what I want to achieve is put some content in my view and have some HTML rendered before and after like this pseudo code:

@widget("MyWidget")
{
   This is the content.
}

MyWidget.cshtml would contain the widget layout and when calling @RenderBody from the layout it would output This is the content.

My current implementation requires me to put the widget content in a separate file from the view and I would like to avoid this.

In my view I can render a widget by calling Html.Partial like this:

<div class="col_6 last">
    @Html.Partial(@"Widgets\MyWidget")
</div>

The partial MyWidget.cshtml only contains the content of the widget and the actual widget "chrome" is placed in a WidgetLayout.cshtml that is referenced from the partial like this:

@{
    Layout = "/Views/Shared/WidgetLayout.cshtml";    
}
<p>   
    This is the widget content.
</p>
Magnus Lindhe
  • 7,157
  • 5
  • 48
  • 60
  • That's what PartialViews, EditorTemplates and DisplayTemplates are here for. I suggest you however, to focus on EditorTemplates, I found them quite flexible than PartialViews. – BigMike Nov 29 '11 at 08:21

1 Answers1

0

You have to create an Html helper that you will use in a using( ) block, similar to using(Html.BeginForm()) that ads a <form> tag at top and </form> at the end

This has also is relevant and has been answered Here

Community
  • 1
  • 1
Mihalis Bagos
  • 2,500
  • 1
  • 22
  • 32