在ASP.NET MVC 4 HtmlHelpers中呈现ASP.NET Web控件

时间:2014-07-11 10:54:16

标签: asp.net asp.net-mvc-4 razor

我在ASP.NET MVC 4中创建自定义HtmlHelper,需要呈现ASP.NET标准Web控件,如<asp:Panel><asp:Button>。我的意思是:从我的HtmlHelper,我希望我的浏览器渲染它们,因为它是一个ASP.NET Web表单应用程序。

我正在网上搜索这个主题,但没有发现任何可能有助于我如何实现这一点的具体内容。

如果有人知道如何实现这一点或对此有任何经验,请分享:)

1 个答案:

答案 0 :(得分:1)

如果有人有类似的问题或想知道如何做到这一点,这是我的代码。

public static MvcHtmlString Panel(this HtmlHelper html)
{
            Panel pnl = new Panel();
            pnl.ID = "mainPanel";
            pnl.BorderStyle = BorderStyle.Solid;
            pnl.BorderWidth = Unit.Pixel(1);
            pnl.BorderColor = System.Drawing.Color.Black;

            Label lblTitle = new Label();
            lblTitle.Text = "Title";
            TextBox txtTitle = new TextBox();
            txtTitle.ID = "txtTitle";
            lblTitle.Attributes.Add("for", "txtTitle");

            Label lblMessage = new Label();
            lblMessage.Text = "Message";
            TextBox txtMessage = new TextBox();
            txtMessage.TextMode = TextBoxMode.MultiLine;
            txtMessage.ID = "txtMessage";

            Label lblDepartment = new Label();
            lblDepartment.Text = "Department";
            DropDownList lstDepartment = new DropDownList();
            lstDepartment.ID = "lstDepartment";
            ListItemCollection collection = new ListItemCollection();
            collection.Add(new ListItem("Department1"));
            collection.Add(new ListItem("Department3"));
            collection.Add(new ListItem("NoDepartment"));

            lstDepartment.DataSource = collection;
            lstDepartment.DataBind();

            pnl.Controls.Add(lblTitle);
            pnl.Controls.Add(txtTitle);
            pnl.Controls.Add(lblMessage);
            pnl.Controls.Add(txtMessage);
            pnl.Controls.Add(lblDepartment);
            pnl.Controls.Add(lstDepartment);

            HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
            pnl.RenderControl(writer);

            return MvcHtmlString.Create(writer.InnerWriter.ToString());
}

基本上,您使用所需的Web控件的类,然后创建HTMLHtmlTextWriter用于呈现您为此目的编码的内容。