views:

235

answers:

1

Is there a generic Html.Element?

I would like to be able to do this:

Html.Element<AccountController>("IFrame", "elementName", new { src = c => c.ChangePassword })
+2  A: 

The most appropriate, "MVC-ish" approach to build HTML content the way you're describing is to create a custom HtmlHelper extension method. This method ought to make use an instance of System.Web.Mvc.TagBuilder to construct the HTML. Here's an example (copied from one of my current projects, but not actually tested in isolation):

using System.Web.Mvc;
using System.Linq;

public static class HtmlHelperExtensions
{
    public static string Element(this HtmlHelper htmlHelper, string tag, string name, object htmlAttributes)
    {
        TagBuilder builder = new TagBuilder(tag);

        builder.GenerateId(name);
        builder.MergeAttributes(htmlAttributes);
        // use builder.AddCssClass(...) to specify CSS class names

        return builder.ToString()
    }
}

// example of using the custom HtmlHelper extension method from within a view:
<%=Html.Element("iframe", "elementName", new { src = "[action url here]" })%>

As for extending your custom HtmlHelper method to support the controller action lambda, this post is a good place to start.

Erik D
You can of course write extension method the way you did it in the first place. To be generic in nature, providing lambda expression for action. This way you'll avoid *magic strings* to make your code runtime error free, because your action will be checked at compile time.
Robert Koritnik