Rendering ASP.NET web controls in ASP.NET MVC 4 HtmlHelpers - asp.net

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.

Related

linq to dropdown list in asp.net [duplicate]

This question already has answers here:
How to bind LINQ data to dropdownlist
(3 answers)
Closed 8 years ago.
can someone help me
Im having issues binding my dropdown list from my sql linq query, theres seems to be issues with anon types not being statically typed and then the list is not being populated
please help thanks
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
//List<Location> thelocations = new List<Location>();
var locations = new[] { from a in dc.Locations select new { a.name } };
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataTextField = "Location";
ddLocation.DataValueField = "Location";
}
Try it:
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
var locations = from a in dc.Locations;
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations.ToList();
ddLocation.DataTextField = "name";
ddLocation.DataValueField = "Id";
ddLocation.DataBind();
}
I hope it will help you.
Try this, You have missed ddLocation.DataBind(); and did't add this dynamic DDL to any Controls and needs to be some changes
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
List<Location> locations = (from a in dc.Locations).ToList();
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataTextField = "name";
ddLocation.DataValueField = "Id";
ddLocation.DataBind();
divRunServer.Controls.Add(ddLocation);
}
add this div tag in client side
<div id="divRunServer" runat="server"></div>
Another way:
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
var locations = from a in dc.Locations select new {a1 = a.Id, a2 = a.name };
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "a1";
ddLocation.DataTextField = "a2";
}
Anonymous types should work fine, you just provided property names for DataTextField and DataValueField that aren't in your anonymous type. Try:
V-- give the property a name
var locations = from a in dc.Locations select new { Location = a.name };
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataTextField = "Location";
ddLocation.DataValueField = "Location";
However I notice you're not doing anything with the DropDownList that you create - you may be unintentionally hiding a page control named ddLocation.

How to render AjaxToolkit controls

I am trying to get the rendered HTML of Ajaxtoolkit:Editor control. I am getting an error while rendering here is my code:
[WebMethod]
public static string GetHtmlEditor()
{
CustomHTMLEditor objCustom = new CustomHTMLEditor();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter textWriter = new HtmlTextWriter(sw);
UpdatePanel up = new UpdatePanel();
up.ID = "upId";
up.ContentTemplateContainer.Controls.Add(objCustom);
up.RenderControl(textWriter);
return textWriter.ToString();
}
Error: Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request.
I tried executing directly i.e without using UpdatePanel. Still it throws the same error.
Can i render Ajaxtoolkit controls?

Render a user control ascx

I want to use an ascx as a template, and render it programatically, using the resulting html as the return value of an ajax method.
Page pageHolder = new Page();
MyUserControl ctlRender = (MyUserControl)pageHolder.LoadControl(typeof(MyUserControl),null);
pageHolder.Controls.Add(ctlRender);
System.IO.StringWriter swOutput = new System.IO.StringWriter();
HttpContext.Current.Server.Execute(pageHolder, swOutput, false);
return swOutput.ToString();
This all executes, and the Page Load event of the user control fires, but the StringWriter is always empty. I've seen similar code to this in other examples, what am I missing?
Have you tried this:
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();
}
Taken directly from the article here:
ASP.NET Tip: Render Control into HTML String
You always have to use something like this.Controls.Add(TemplateControl.LoadControl("~/PathTo/YourControl.ascx")
The reason is, that there is no internal mapping of Types to there ascx-file (only the other way arround). So this means if you initialize new YourControl(), it will not do anything you defined in the ascx part. If you would have
protected override void protected override void Render(HtmlTextWriter output) {
output.WriteLine("Test");
}
this would give you "Test" in the place you rendered your control to.

is there a way to email all input controls values in asp.net

I am looking for a way to email all the values entered by a user into a form. Does this exist in asp.net ?
here is my email code:
Dim messagemain As String = emailbody
Dim message As New MailMessage()
message.IsBodyHtml = True
message.From = New MailAddress("foo#foo.com")
message.To.Add(New MailAddress("foo#foo.com"))
message.Subject = ("Response from form")
message.Body = (messagemain)
Dim client As New SmtpClient()
client.Host = "email.foo.foo"
client.Send(message)
I usually go through manually and ad all the necessaries to the emailbody var then send, but this form has over 200 fields.
Thanks.
You may try too looping over the Controls collection of the page and if you find a textbox add its value to the mail body:
var body = new StringBuilder();
foreach (var control in pageInstance.Controls)
{
if (control is TextBox)
{
var value = ((TextBox)control).Text;
body.AppendFormat("value: {0}<br/>", HttpUtility.HtmlEncode(value));
}
}
message.Body = body.ToString();
Remark: This will work only if the text boxes are directly placed on the page and not inside some other containers such as panels, ... In order to take this into account you could write a recursive function that visits all the controls.
Well instead of building it manually this migth help you if you need all values of the form.
var sb = new StringBuilder();
foreach (string key in this.Request.Form.Keys)
sb.AppendFormat("{0} = {1}<br/>", key, this.Request.Form[key]);
var emailbody = sb.ToString();

ASP.NET: Shortest way to render DataTable to a string (HTML)?

What is the shortest way to convert a DataTable into a string (formatted in HTML)?
Programmatically binding to a UI control and rendering to an ASP.NET page is not acceptable. Can't depend on the ASP.NET page lifecycle.
The purpose of this shouldn't matter, but to satisfy curiosity: This is for logging/debugging/dump purposes in algorithms that do a lot of DataTable processing.
Thanks!
You can use the ASP.net controls such as GridView, DataGrid and point them render into StringBuilder using StringWriter, No need to use ASP.net page for this, this is a simple example in Console
class Program
{
static void Main(string[] args)
{
IList<Person> persons = new List<Person>()
{
new Person{Id = 1, Name="Test Name 1"},
new Person{Id = 2, Name="Test Name 2"}
};
GridView gridView = new GridView();
StringBuilder result = new StringBuilder();
StringWriter writer = new StringWriter(result);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
gridView.DataSource = persons;
gridView.DataBind();
gridView.RenderControl(htmlWriter);
Console.WriteLine(result);
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
I use this function through my application. It's pretty straightforward
static public string ConvertDataTableToHTMLString(System.Data.DataTable dt, string filter, string sort, string fontsize, string border, bool headers, bool useCaptionForHeaders)
{
StringBuilder sb = new StringBuilder();
sb.Append("<table border='" + border + "'b>");
if (headers)
{
//write column headings
sb.Append("<tr>");
foreach (System.Data.DataColumn dc in dt.Columns)
{
if (useCaptionForHeaders)
sb.Append("<td><b><font face=Arial size=2>" + dc.Caption + "</font></b></td>");
else
sb.Append("<td><b><font face=Arial size=2>" + dc.ColumnName + "</font></b></td>");
}
sb.Append("</tr>");
}
//write table data
foreach (System.Data.DataRow dr in dt.Select(filter,sort))
{
sb.Append("<tr>");
foreach (System.Data.DataColumn dc in dt.Columns)
{
sb.Append("<td><font face=Arial size=" + fontsize + ">" + dr[dc].ToString() + "</font></td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
return sb.ToString();
}
If this is just for purposes of logging, might it not make more sense to log them out as XML - easier to manipulate if you need to. You just need to call the WriteXml method.
Create the control, create an HTML Writer, set any settings or databind the control, then call the render method, using the HTML Writer.
You can then get the string out of the writer.
Edit: I initially misread the question and thought you wanted to render a datagrid.
A Datatable can easily be rendered to its XML.
you asked for HTML.
here is a console app code that will render a datatable using a datagrid control.
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Rows.Add("RowValue1", "Field2RowValue1");
dt.Rows.Add("RowValue2", "Field2RowValue2");
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
dg.RenderControl(w);
Console.Write(sw.ToString());
Console.ReadLine();
}
}

Resources