简体   繁体   中英

Rendering ASP.NET web controls in ASP.NET MVC 4 HtmlHelpers

I am creating custom HtmlHelper in ASP.NET MVC 4 that needs to render ASP.NET standard web controls like <asp:Panel> or <asp:Button> . What I mean by this is: from my HtmlHelper, I want my browser to render them same as it is a ASP.NET web form application.

I was searching on the net about this topic, but didn't find anything specific that might help me how to realize this.

If anyone has any idea how this can be realized or has any experience with this, please share it :)

If anyone has similar problem or wants to know how it can be done, here is my code.

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

Basically, you use the classes of the web controls you need and you create the HTML . HtmlTextWriter is used to render the things you coded for that purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM