How to send an xml serialized object from ASP.NET to Silverlight - c#

On the button click on an ASP.NET page, I need to load a silverlight application, passing a serialized object from ASP.NET codebehind to MainPage.xaml.cs. How to do this?

Why not use WCF? This is a perfect fit for sending serialized objects. Also, WCF hosts well on IIS, so it works great with ASP. Here is a tutorial to get you started. You should be able to see clearly how to define a simply API that you can call from Silverlight. You just need to make your object part of a DataContract.

Do either of these help - http://www.silverlight.net/archives/videos/using-startup-parameters-with-silverlight or http://forums.silverlight.net/t/183963.aspx/1 ?

Some options for you, may help. You could use Javascript - silverlight.net on scripting Silverlight to reach inside the Silverlight object from your page.
Another option is to have the Silverlight object access the AspNet page to ask for it's xml using PageMethods. ( System.Web.Services.WebMethod) once it's loaded.

One option is to configure a Silverlight onLoad event in the <object> tag for your app:
<param name="onLoad" value="setInfo" />
Then use script to push the XML into your app (dynamically insert the XML onto the page from ASP.NET):
<script type="text/javascript">
function setInfo(sender) {
var msg = '<yourtag>your info here</yourtag>';
sender.getHost().content.Page.SetInfo(msg);
}
</script>
To allow script to call your app, configure as follows:
public MainPage()
{
HtmlPage.RegisterScriptableObject("Page", this);
InitializeComponent();
}
[ScriptableMember]
public void SetInfo(string xml)
{
// do stuff
}

Register onLoad param in your Silverlight <Object> tag:
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
<param name="source" value="ClientBin/MySlApp.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50826.0" />
<param name="autoUpgrade" value="true" />
<param name="onLoad" value="onSilverlightLoad" />
</object>
and register <Script>
<script type="text/javascript">
function onSilverlightLoad(sender, args)
{
var mySlControl = sender.getHost();
mySlControl.content.Communicator.MyDeserializer("SerializedObjectString")
}
</script>
In your Silverlight app register `Communicator' object so it is the app itself:
namespace MySilverlightApp
{
public MySilverlightApp()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Communicator", this);
}
}
and create de-serialization function decorated with [ScriptableMember]:
[ScriptableMember]
public void MyDeserializer(string _stringPassedFromHtmlDocument)
{
//deserialize _stringPassedFromHtmlDocument
}
I have above working in one of Sharepoint projects utilising Silverlight webpart. Serialized object is however rendered into HTML so not sure if that will work for your Button.Click() requirement. One thing though should you go down this route: I encountered many many many issues when trying XML serialization and found JSON to be better alternative.

In your MainPage.xaml.cs, define a property getter/setter for whatever object type you need passed.
In your ASP.NET page button click handler, set the property to the serialized object.
If you need this to maintain the serialized object after the page lifecycle finishes, simply change the property setter in MainPage.xaml.cs to persist the serialized object across page lifecycles.
Hope this helps.
Pete

There are two possible paths here:
1) When the button is pressed, the page posts back to the server, gathers some information, serializes it into XML, shows the silverlight component, which then loads the serialized XML.
2) When the page is loaded, the XML data is available. Pressing the button simply shows the silverlight component and asks it to load the XML data.
Scenario 1
Here are the steps that you need to take for scenario 1.
1) Add the silverlight component to the page and embed it in a container (div, table, whatever you like) that is set to runat server. Note that we also specify an onload param to fire a specific event when the silverlight object has finished loading:
<div id="divDiagram" runat="server">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
id="objDiagram">
<param name="onLoad" value="RefreshDiagram" />
</object>
</div>
2) In your code-behind, hide this container until the button is pressed. For example:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
divDiagram.Visible = false;
}
}
void Button1_Click(object sender, EventArgs e)
{
divDiagram.Visible = true;
}
3) Add a hidden input to hold the serialized data:
<input type="hidden" id="txtSerializedData" runat="server" />
4) Set the contents of this input on the button click:
txtSerializedData.Value = "some serialized data";
5) Modify the silverlight components code to expose the control to javascript:
public MainPage()
{
InitializeComponent();
System.Windows.Browser.HtmlPage.RegisterScriptableObject("DiagramPage", this);
}
6) Add a method to the silverlight control that can be called from javascript (this is the ScriptableMember attribute) to get the serializable content and work with it:
[System.Windows.Browser.ScriptableMember()]
public void RefreshDiagram()
{
// Fetch the hidden input control from the page
var serializedElement = System.Windows.Browser.HtmlPage.Document.GetElementById("txtSerializedData");
// Then fetch its value attribute
var sSerializedData = serializedElement.GetAttribute("value");
// Finally, do something with sSerializedData
}
7) Finally, add the javascript method to the page that is fired when the silverlight control is loaded:
<script type="text/javascript">
function GetDiagramPageContent() {
/// <summary>This method retrieves the diagram page object content</summary>
// Exceptions are handled by the caller
var oObject = document.getElementById('objDiagram');
if (oObject) {
return oObject.Content;
} else {
return null;
}
}
function RefreshDiagram() {
try {
var oContent = GetDiagramPageContent();
try {
// If we don't have content or a diagram page, bail
if ((oContent == null) || (oContent.DiagramPage == null)) {
return;
}
} catch (ex) {
return;
}
// Now ask the control to refresh the diagram
oContent.DiagramPage.RefreshDiagram();
} catch (ex) {
alert('Javascript Error (RefreshDiagram)\r' + ex.message);
}
}
</script>
Scenario 2
Scenario 2 is very similar to scenario 1, with the following changes:
1) Do not include the onLoad param in the silverlight object. Instead, call the RefreshDiagram javascript method from the client-side button click.
2) Do not show or hide the containing div in code-behind. Instead, use the style attributes to control the visibility:
<div id="divDiagram" runat="server" style="visibility: hidden; visibility: visible">
and in the javascript button click event:
var oDiv = document.getElementById("divDiagram");
oDiv.style.visibility = "";
oDiv.style.display = "";
3) Load the hidden text box in pageload instead of on the server-side button click.

This might help
Passing Objects between ASP.NET ans Silverlight Controls
best regards

You can use this thing called SilverlightSerializer by Mike Talbot

Related

Assigning objects within public method

I wish to create a public method on my masterpage, that I can call from within every subpage.
I am trying to wrap my head around how this should be done.
On my subpages I've made this method to fill a panel with an errormessage.
protected void errorMessage (string errorText) {
HtmlGenericControl divTag = new HtmlGenericControl("div");
Panel_Name.Controls.Add(divTag);
divTag.InnerHtml = errorText;
}
Now if I were to make this function public on my masterpage, It wont recognize my Panel as it havent been showed yet. I'm guessing the answer involves FindControl
(Sorry for my rubbish code english)
How should I do this ?
To be fair, for your scenario, I would use a UserControl (.ascx) on your Pages (.aspx).
Then, in the UserControl, have your error message markup, such as:
Code front (ErrorMessage.ascx)
<asp:Panel runat="server" ID="PanelErrorMessage" /> // creates a <div>
Code behind (ErrorMessage.ascx.cs)
public string ErrorMessage
{
get {}
set
{
PanelErrorMessage.Text = value; // sets the panel text (<div>text</div>) to value when property is set
}
}
Use your UserControl on your Page (you'll need to define this as a control tag on your page too with the prefix/suffix):
<myControls:ErrorMessage runat="server" ID="MyErrorControl" />
You can also do this in many places on your page, if you require different errors.
Then, when you have an error, you'll simply do:
MyErrorControl.ErrorMessage = "This is my error message";
Job done!

How to check whether postback caused by a Dynamic link button

I have a button control. On click of this button I need to add a Link Button dynamically. The Link Button needs an event handler. Hence the dynamic Link button is first added in the Page_Load and cleared and added again in the button click handler. Please read Dynamic Control’s Event Handler’s Working for understanding the business requirement for this.
I have read On postback, how can I check which control cause postback in Page_Init event for identifying the control that caused the postback (inside Page_Load). But it is not working for my scenario.
What change need to be done to confirm whether the postback was caused by link button (inside Page_Load)?
Note: Refer the following for another scenario where it is inevitable https://codereview.stackexchange.com/questions/20510/custom-paging-in-asp-net-web-application
Note 1: I need to get the postback control ID as the first step inside if (Page.IsPostBack). I need to add the dynamic link buttons control only if it is a postback from the button or the link button. There will be other controls that causes postback. For such postbacks we should not execute this code.
Note 2: I am getting empty string for Request["__EVENTARGUMENT"] in the Page_Load
Related Question: By what event, the dynamic controls will be available in the Page (for using in FindControl). #Tung says - "Your GetPostBackControlId method is properly getting the name of the control that caused the postback, but it is unable to find a control with that id through page.FindControl because the linkbutton has not been created yet, and so page does not know of its existence. "
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PostbackTest.aspx.cs" Inherits="PostbackTest"
MasterPageFile="~/TestMasterPage.master" %>
<asp:Content ID="myContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="holder" runat="server">
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="TestClick" />
</asp:Content>
CODE BEHIND
public partial class PostbackTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string IDValue = GetPostBackControlId(this.Page);
int x = 0;
holder.Controls.Clear();
LinkButton lnkDynamic = new LinkButton();
lnkDynamic.Click += new EventHandler(LinkClick);
lnkDynamic.ID = "lnkDynamic123";
lnkDynamic.Text = "lnkDynamic123";
holder.Controls.Add(lnkDynamic);
}
}
protected void TestClick(object sender, EventArgs e)
{
holder.Controls.Clear();
LinkButton lnkDynamic = new LinkButton();
lnkDynamic.Click += new EventHandler(LinkClick);
lnkDynamic.ID = "lnkDynamic123";
lnkDynamic.Text = "lnkDynamic123";
holder.Controls.Add(lnkDynamic);
}
protected void LinkClick(object sender, EventArgs e)
{
}
public static string GetPostBackControlId(Page page)
{
if (!page.IsPostBack)
{
return string.Empty;
}
Control control = null;
// First check the "__EVENTTARGET" for controls with "_doPostBack" function
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type
string controlId;
Control foundControl;
foreach (string ctl in page.Request.Form)
{
// Handle ImageButton they having an additional "quasi-property" in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is Button || foundControl is ImageButton)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
}
REFERENCE
On postback, how can I check which control cause postback in Page_Init event
Dynamic Control’s Event Handler’s Working
Understanding the JavaScript __doPostBack Function
Access JavaScript variables on PostBack using ASP.NET Code
How does ASP.NET know which event to fire during a postback?
how to remove 'name' attribute from server controls?
How to use __doPostBack()
A postback in asp.net is done by the java script function __doPostback(source, parameter)
so in your case it would be
__doPostback("lnkDynamic123","") something like this
So in the code behind do the following
var btnTrigger = Request["__EVENTTARGET"];
if(btnTrigger=="lnkDynamic123")
{
}
--- this would tell that it is your linkbutton that causes the postback
You can move the call to the GetPostBackControlId method after the LinkButton has been added to the page:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
holder.Controls.Clear();
LinkButton lnkDynamic = new LinkButton();
lnkDynamic.Click += new EventHandler(LinkClick);
lnkDynamic.ID = "lnkDynamic123";
lnkDynamic.Text = "lnkDynamic123";
holder.Controls.Add(lnkDynamic);
string IDValue = GetPostBackControlId(this.Page);
if (IDValue == lnkDynamic.ID)
LinkClick(lnkDynamic, new EventArgs());
}
}
Calling the click event handler here also more closely mimics the standard ASP.NET Page Life Cycle, where Postback event handling occurs after the Load event.
Edit:
If the control ID must be determined before the LinkButtons are created, you can create a naming scheme for the link button IDs, e.g. lnkDynamic_1, lnkDynamic_2 etc.
Request["__EVENTTARGET"] will then contain the auto-generated control ID such as “ctl00$mc$lnkDynamic_1”, which you can use to identify which LinkButton caused the postback.
If You're getting the post back control id correctly but FindControl returns nothing, then it's probably because You're using a master page. Basically, someControl.FindControl(id) searches through controls that are in someControl.NamingContainer naming container. But in Your case, the Button1 control is in the ContentPlaceHolder1, which is a naming container, and not directly in the Page naming container, so You won't find it by invoking Page.FindControl. If You can't predict in which naming container the control You're looking for is going to be (e.g. post back can be caused by two different buttons from two different content placeholders), then You can write an extension that'll search for a control recursively, like so:
public static class Extensions
{
public static Control FindControlRecursively(this Control control, string id)
{
if (control.ID == id)
return control;
Control result = default(Control);
foreach (Control child in control.Controls)
{
result = child.FindControlRecursively(id);
if (result != default(Control)) break;
}
return result;
}
}
Use it with caution though, because this method will return the first control that it finds with the specified id (and You can have multiple controls with the same id - but they should be in different naming containers; naming containers are meant to differentiate between controls with same ids, just as namespaces are meant to differentiate between classes with same names).
Alternatively, You could try to use FindControl(string id, int pathOffset) overload, but I think it's pretty tricky.
Also, check this question out.
First approach (wouldn't recommend but it's more flexible)
One completely different approach - although I don't really feel like I should promote it - is to add a hidden field to the form.
The value of this hidden field might be something like false by default.
In case of clicking one of the dynamic buttons which should cause the dynamic controls to be added again, you can simply change the hidden fields value to true on client side before performing the postback (eventually you want/have to modify the client side onclick handler to make this happen).
Of course it would be possible to store more information in such a field, like the controls id and the argument (but you can get those values as described in the other answers). No naming schema would be required in this case.
This hidden field could be "static". So it would be accessible in code behind all time. Anyhow, you might want to implement something to make sure that nobody is playing around with its values and fakes a callback which looks like it originated from one of these dynamic links.
However, this whole approach just helps you getting the id of the control. Until you create the control again, you won't be able to get the instance through NamingContainer.FindControl (as mentioned in the other answers already ;)). And in case you create it, you don't need to find it anymore.
Second approach (might not be suitable due to its contraints)
If you want to do it the clean way, you need to create your controls OnLoad, no matter if something was clicked or not. Additionally, the dynamic controls ID has to be the same as the one you sent to the client in the first place. You subscribe to its Click or Command event and set its visibility to false. Inside the click event handler, you set the senders visibility to true again. This implies, that you don't care if that link is created but instead just don't want to send it to the client. The example below only works for a single link of course (but you could easily modify it to cover a whole group of links).
public void Page_Load(object sender, EventArgs e)
{
LinkButton dynamicButton = new LinkButton();
dynamicButton.ID = "linkDynamic123";
// this id needs to be the same as it was when you
// first sent the page containing the dynamic link to the client
dynamicButton.Click += DynamicButton_Click;
dynamicButton.Visible = false;
Controls.Add(dynamicButton);
}
public void DynamicButton_Click(object sender, EventArgs e)
{
// as you created the control during Page.Load, this event will be fired.
((LinkButton)sender).Visible = true;
}

How to Check if ListBox is Empty on Client-Side

I created a javascript confirm as below.
<script Type="Text/Javascript">
function CheckListBox(lvi)
{
if(lvi == "")
{
if(confirm("Are you sure?"))
{
return true;
}
else
{
return false;
}
}
}
</script>
I need to test if the ListBox.Items control is empty... I already made reference on my aspx page
<script language="javascript" type="text/javascript" src="/JS/confirm.js"></script>
I want to know how to call it on my aspx.cs page . . . So I can pass the parameter:
string oi = Listbox_Clubes.Items.Count.ToString();//Its the parameter I want to pass
See this link for how to execute javascript from code behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "CheckListBox(" + Listbox_Clubes.Items.Count.ToString() + ");", false);
}
Note: you must add a ScriptManager control in aspx page.
For your javascript, you can get the value without the code-behind (this assumes the script code is in the same page, in order to get the client ID):
<script>
function ClickListBox() {
if ($("#<%= Listbox_Clubes.ClientID %>").val() === null) {
if (confirm("Are you sure?")) {
return true;
}
else {
return false;
}
}
}
</script>
Similarly, you don't use javascript to validate on the server side. The code you posted will return all items in the ListBox. Here is one way to get the count of the number of selected items (I'm using .ToString() based on the OP code example):
string oi = Listbox_Clubes.Items.Cast<ListItem>().Where(i => i.Selected).Count().ToString();
However, there is no reason why you would get this value and pass it back to the client-side to do validation (what it sounds like you want to do in your post). Mainly because this involves a post-back, and client-side validation, by its nature, should occur before post-back. Also, you will still need to do server-side validation, even when you have client-side validation.
Related: in the code-behind, you can test to see if anything is selected by:
bool hasValue = Listbox_Clubes.SelectedItem != null;
The .SelectedItem returns the selected item with the lowest index in the list control. When nothing is selected, this value is null... so you know if the value isn't null, then at least one item was selected.
If you want to require that they choose at least one item, you can use a RequireFieldValidator and let that handle both validations. If you haven't done much with ASP.NET validators, that would be one good thing to read up on.
It sounds like you probably should read more about client-side validation and server-side validation and how to use them... because it seems like you are mixing them up.
The count code is a modified version of code in ASP:ListBox Get Selected Items - One Liner?

Acess controls on ContentPages via Javascript by MasterPage

I need my MasterPage to be able to get ControlIDs of Controls on ContentPages, but I cannot
use <%= xxx.CLIENTID%> as it would return an error as the control(s) might not be loaded by the contentplaceholder.
Some controls have a so called BehaviourID, which is exactly what I would need as they can be directly accessed with the ID:
[Asp.net does always create unique IDs, thus modifies the ID I entered]
Unfortunately I need to access
e.g. ASP.NET Control with BehaviouraID="test"
....
document.getElementById("test")
if I were to use e.g. Label control with ID="asd"
....
document.getElementById('<%= asd.ClientID%>')
But if the Labelcontrol isn't present on the contentpage, I of course get an error on my masterpage.
I need a solution based on javascript. (server-side)
Thx :-)
You could use jQuery and access the controls via another attribute other than the ID of the control. e.g.
<asp:Label id="Label1" runat="server" bid="test" />
$('span[bid=test]')
The jQuery selector, will select the span tag with bid="test". (Label renders as span).
Best solution so far:
var HiddenButtonID = '<%= MainContent.FindControl("btnLoadGridview")!=null?
MainContent.FindControl("btnLoadGridview").ClientID:"" %>';
if (HiddenButtonID != "") {
var HiddenButton = document.getElementById(HiddenButtonID);
HiddenButton.click();
}
Where MainContent is the contentplace holder.
By http://forums.asp.net/members/sansan.aspx
You could write an json-object with all the control-ids which are present on the content-page and "register" that object in the global-scope of your page.
Some pseudo pseudo-code, because I can't test it at the moment...
void Page_Load(object sender,EventArgs e) {
System.Text.StringBuilder clientIDs = new System.Text.StringBuilder();
IEnumerator myEnumerator = Controls.GetEnumerator();
while(myEnumerator.MoveNext()) {
Control myControl = (Control) myEnumerator.Current;
clientIDs.AppendFormat("\t\"{0}\" : \"{1}\",\n", myControl.ID, myControl.ClientID);
}
page.ClientScript.RegisterStartupScript(page.GetType(),
"ClientId",
"window.ClientIDs = {" + clientIDs.ToString().Substring(0, clientIDs.ToString().Length - 2) + "};",
true);
}
It sounds like your issue is that you are using the master page for something it wasn't intended. The master page is a control just like any other control, and therefore cannot access any of the controls of its parent (the page). More info:
ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps
My suggestion is to inject the JavaScript from your page where the controls can actually be resolved. Here is a sample of how this can be done:
#Region " LoadJavaScript "
Private Sub LoadJavaScript()
Dim sb As New StringBuilder
'Build the JavaScript here...
sb.AppendFormat(" ctl = getObjectById('{0});", Me.asd.ClientID)
sb.AppendLine(" ctl.className = 'MyClass';")
'This line adds the javascript to the page including the script tags.
Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "MyName", sb.ToString, True)
'Alternatively, you can add the code directly to the header, but
'you will need to add your own script tags to the StringBuilder before
'running this line. This works even if the header is in a Master Page.
'Page.Header.Controls.Add(New LiteralControl(sb.ToString))
End Sub
#End Region

Self closing Html Generic Control?

I am writing a bit of code to add a link tag to the head tag in the code behind... i.e.
HtmlGenericControl css = new HtmlGenericControl("link");
css.Attributes["rel"] = "Stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["href"] = String.Format("/Assets/CSS/{0}", cssFile);
to try and achieve something like...
<link rel="Stylesheet" type="text/css" href="/CSS/Blah.css" />
I am using the HtmlGenericControl to achieve this... the issue I am having is that the control ultimatly gets rendered as...
<link rel="Stylesheet" type="text/css" href="/CSS/Blah.css"></link>
I cant seem to find what I am missing to not render the additional </link>, I assumed it should be a property on the object.
Am I missing something or is this just not possible with this control?
I think you'd have to derive from HtmlGenericControl, and override the Render method.
You'll then be able to write out the "/>" yourself (or you can use HtmlTextWriter's SelfClosingTagEnd constant).
Edit: Here's an example (in VB)
While trying to write a workaround for umbraco.library:RegisterStyleSheetFile(string key, string url) I ended up with the same question as the OP and found the following.
According to the specs, the link tag is a void element. It cannot have any content, but can be self closing. The W3C validator did not validate <link></link> as correct html5.
Apparently
HtmlGenericControl css = new HtmlGenericControl("link");
is rendered by default as <link></link>. Using the specific control for the link tag solved my problem:
HtmlLink css = new HtmlLink();
It produces the mark-up <link/> which was validated as correct xhtml and html5.
In addition to link, System.Web.UI.HtmlControls contains classes for other void element controls, such as img, input and meta.
Alternatively you can use Page.ParseControl(string), which gives you a control with the same contents as the string you pass.
I'm actually doing this exact same thing in my current project. Of course it requires a reference to the current page, (the handler), but that shouldn't pose any problems.
The only caveat in this method, as I see it, is that you don't get any "OO"-approach for creating your control (eg. control.Attributes.Add("href", theValue") etc.)
I just created a solution for this, based on Ragaraths comments in another forum:
http://forums.asp.net/p/1537143/3737667.aspx
Override the HtmlGenericControl with this
protected override void Render(HtmlTextWriter writer)
{
if (this.Controls.Count > 0)
base.Render(writer); // render in normal way
else
{
writer.Write(HtmlTextWriter.TagLeftChar + this.TagName); // render opening tag
Attributes.Render(writer); // Add the attributes.
writer.Write(HtmlTextWriter.SelfClosingTagEnd); // render closing tag
}
writer.Write(Environment.NewLine); // make it one per line
}
The slightly hacky way.
Put the control inside a PlaceHolder element.
In the code behind hijack the render method of the PlaceHolder.
Render the PlaceHolders content exactly as you wish.
This is page / control specific and does not require any overrides. So it has minimal impact on the rest of your system.
<asp:PlaceHolder ID="myPlaceHolder" runat="server">
<hr id="someElement" runat="server" />
</asp:PlaceHolder>
protected void Page_Init(object sender, EventArgs e)
{
myPlaceHolder.SetRenderMethodDelegate(ClosingRenderMethod);
}
protected void ClosingRenderMethod(HtmlTextWriter output, Control container)
{
var voidTags = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "br", "hr", "link", "img" };
foreach (Control child in container.Controls)
{
var generic = child as HtmlGenericControl;
if (generic != null && voidTags.Contains(generic.TagName))
{
output.WriteBeginTag(generic.TagName);
output.WriteAttribute("id", generic.ClientID);
generic.Attributes.Render(output);
output.Write(HtmlTextWriter.SelfClosingTagEnd);
}
else
{
child.RenderControl(output);
}
}
}

Categories