Reputation: 9445
I am creating AJAX enabled reusable controls in MVC razor code. It uses a Controller and 1 or more Razor views to work. What is the best practice for isolating those code files from the rest of my project? Logically, it does not make sense to me to have the Controller and the Views mixed in the with main Controller and View files I use for the rest of the project.
And what if i wanted to reuse the control?
Upvotes: 1
Views: 118
Reputation: 42333
I would probably make an extension method off HtmlHelper, so you can use it by calling:
@Html.MyControl("blah", "blah")
from within your view. This is how my MarkdownHelper works (though it's not actually a control, it just formats some text). This is also how the built-in stuff tends to work (g. Html.TextBox, etc.):
/// <summary>
/// Helper class for transforming Markdown.
/// </summary>
public static partial class MarkdownHelper
{
/// <summary>
/// Transforms a string of Markdown into HTML.
/// </summary>
/// <param name="helper">HtmlHelper - Not used, but required to make this an extension method.</param>
/// <param name="text">The Markdown that should be transformed.</param>
/// <returns>The HTML representation of the supplied Markdown.</returns>
public static IHtmlString Markdown(this HtmlHelper helper, string text)
{
// Transform the supplied text (Markdown) into HTML.
var markdownTransformer = new Markdown();
string html = markdownTransformer.Transform(text);
// Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
return new MvcHtmlString(html);
}
}
Upvotes: 1