Bundling a Controller and Views to create a User Control in MVC .NET
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 p开发者_如何学Pythonroject? 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?
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);
}
}
精彩评论