开发者

ASP.NET MVC Html.Element?

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 })


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜