0

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 })
1
  • 3
    Can't you just do <iframe/> directly? If you need ChangePassword to be converted to string URL you can use Html.BuildUrlFromExpression. Commented Dec 22, 2009 at 15:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.