Asp.net control to HTML - c#

I'm just trying to get the equivalent HTML code that represent a specific control in asp.
for example i have the following label in ASP
Label x=new Label();
x.ID="a123";
x.Text="b123";
i just want to find a way to get
"<span id='a123'>b123</span>"

You can use this method to render controls to html.
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
And use
Label x = new Label();
x.ID = "a123";
x.Text = "b123";
var html = RenderControl(x);
will give you <span id="a123">b123</span>

Related

Insert Link Button In String Builder

I created a dynamic link button, which needs to be inserted in a StringBuilder to not ruin the design of my aspx page.
So here's a "part" of my code where I need to insert my LinkButton:
design.Append("<h3>");
NewAddToCart(); //This is where my linkbutton should be inserted
design.Append("</h3></div>");
My NewAddToCart() is constructed on the following code:
private void NewAddToCart()
{
LinkButton lbtnAddtoCart = new LinkButton();
lbtnAddtoCart.ID = "lbtnCart" + i;
lbtnAddtoCart.CommandArgument = i.ToString();
lbtnAddtoCart.CssClass = "glyphicon glyphicon-shopping-cart pull-right";
lbtnAddtoCart.Click+=lbtnAddtoCart_Click;
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter html = new HtmlTextWriter(sw))
{
lbtnAddtoCart.RenderControl(html);
}
}
}

Barcode number under generated Barcode using Barcode Rendering Framework in web application

Following is my previous question that is working fine and generating the barcode.
My previous Question
Now, I just want the characters(forming the barcode) to be written under this barcode(image). How can i achieive that.? I am using Barcode Rendering Framework for generating the barcode. Please help.
Can I do it by taking a panel and adding the image and the text(barcode characters) and printing the panel.??
I did it by using asp panel in which i added the barcode image that is created. Under that I added the string i.e my barcode characters. Then using the print helper function I am able to print them.
Following is my code for adding image and text to panel.
Code39BarcodeDraw barcode39 = BarcodeDrawFactory.Code39WithoutChecksum;
// Panel pnl = new Panel();
Label str = new Label();
str.Text="SER1012308131";
// System.Drawing.Image img = barcode39.Draw("SER1012308131", 40);
//string path = Server.MapPath("~/Uploads/") + img+".jpeg";
string path = #"~/Uploads/abcd.jpeg";
// img.Save(path);
Image imgg = new Image();
imgg.ImageUrl=path;
pnlpnl.Width = Unit.Pixel(300);
pnlpnl.Height = Unit.Pixel(45);
pnlpnl.Controls.Add(imgg);
pnlpnl.Controls.Add(str);
Session["ctrl"] = pnlpnl;
ClientScript.RegisterStartupScript
(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=45px,width=300px,scrollbars=1');</script>");
Print helper function.
public PrintHelper()
{
}
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}
public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>");
HttpContext.Current.Response.End();
}

How can I get a server-side control's tag?

How can I get a server-side control's tag? I'm guessing it's something like below:
TextBox textBox=new TextBox();
GetTag(TextBox textBox)
{
...
}
And the result is something like <asp:TextBox /> (the control's design time tag).
When I change the control to CheckBox then the result should be something like <asp:CheckBox />.
There are no methods that can return these tags for you but constructing a dictionary your self should be easy enough.
Dictionary<Type, string> d = new Dictionary<Type, string>();
d.Add(typeof(TextBox), #"<\asp:TextBox />");
TextBox t = new TextBox();
string tag= (d[t.GetType()]);
And so on...
You can use RenderControl method
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
{
textBox.RenderControl(textWriter);
}
}
sb will have textBox's html content.
Edit:
You can get aspx content and find element tag. like this:
String path = Server.MapPath("~/[aspx path]");
string content = File.ReadAllText(path);
string controlID = "textBox";
int startIndex = content.IndexOf("<asp:TextBox ID=\"" + controlID + "\"");
bool foundEndTag = false;
string controlTag = "";
int i = startIndex;
while (!foundEndTag)
{
if (content[i] == '>')
foundEndTag = true;
controlTag += content[i];
i++;
}

How to get HTML of HtmlControl object in backend

I have a short snippet of C# code like this:
HtmlGenericControl titleH3 = new HtmlGenericControl("h3");
titleH3.Attributes.Add("class", "accordion");
HtmlAnchor titleAnchor = new HtmlAnchor();
titleAnchor.HRef = "#";
titleAnchor.InnerText = "Foo Bar";
titleH3.Controls.Add(titleAnchor);
What I want is a way to return a string that looks like this:
<h3 class="accordion">Foo Bar</h3>
Any thoughts or suggestions?
This is the method that I have used in the past to get a control's rendered HTML ahead of time (make sure to include System.IO):
protected string ControlToHtml(Control c)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
c.RenderControl(htmlWriter);
return sw.ToString();
}
Returns this for your test case:
<h3 class="accordion">Foo Bar</h3>
Here is an example that you can use to extend any HtmlControl to have a Render() method:
public static string Render(this HtmlAnchor TheAnchor)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
TheAnchor.RenderControl(htmlWriter);
return sw.ToString();
}
Shouldn't there be a Render method that forces it to emit its own HTML?

Returning an HtmlTable to be written with ajax

I'd like to programmatically build an HtmlTable/Table in the code behind of a webservice and have it return as a string of HTML so that it can be written with JavaScript to the innerhtml of a span/div/whatever
Something similar to the following:
//webservice.amsx.cs Build the table, called by another/different method
protected string Table_Maker()
{
HtmlTable tbl = new HtmlTable();
HtmlTableCell cell = new HtmlTableCell();
HtmlTableRow row = new HtmlTableRow();
cell.InnerText = "WhateverText";
row.Cells.Add(cell);
tbl.Rows.Add(row);
return tbl.ToString();
}
//somepage.aspx write table to the div
function menuHelper(toplayer, toplayernumber)
{
var sublayertable;
var sublayerpostcompileID;
var toplayernumber;
menuHelper_Part1();
function menuHelper_Part1()
{
//replace ucMainMenu with ucMainMenu_pnlContent
sublayerpostcompileID = toplayer.replace("ucMainMenu", "ucMainMenu_pnlContent");
//Call the webmethod
webbernetz.MenuHelperWebService.Sub_Menu_Helper(toplayernumber, menuHelper_Part2);
}
function menuHelper_Part2(result){
//Write the result to the target area
document.getElementById(sublayerpostcompileID).innerHTML = result;
}
}
When I return it to the javascript the javascript simply writes "System.Web.UI.HtmlControls.HtmlTable".
How di I get it to write the actual table?
The only issue with your code is the use of tbl.ToString().
As noted in some of the other posts, you should Render the table control using an HtmlTextWriter to a StringBuilder object, which can then return a string value for your method. Something like this:
protected string Table_Maker() {
HtmlTable tbl = new HtmlTable();
HtmlTableCell cell = new HtmlTableCell();
HtmlTableRow row = new HtmlTableRow();
cell.InnerText = "WhateverText";
row.Cells.Add(cell);
tbl.Rows.Add(row);
StringBuilder sb = new StringBuilder();
using( StringWriter sw = new StringWriter( sb ) ) {
using( HtmlTextWriter tw = new HtmlTextWriter( sw ) ) {
tbl.RenderControl( tw );
}
}
return sb.ToString();
}
That should return the HTML to be inserted into your page.
The problem here is that the HtmlTable.ToString method that you are using is not appropriate for what you want. 'ToString' returns a String that represents the current Object. In this case you have to Render the table first to an HTMLTextWriter and then you can use the method ToString.
Just use tbl.InnerHtml, instead of ToString
Sounds like you are making it more complicated than it needs to be. How about not using the HtmlTable object and just building a string containing the html you need to output.
There is a RenderControl() method that you can call on any control. Or if you are not using HtmlTable to do anything with it other then building HTML then use HtmlTextWriter.

Categories