Get dynamically generated Controls of current Page - c#

I have a MasterPage website. I'll use the Facebook example to simplify understanding of my purpose.
In default.aspx, i add many DIVs dynamically from code-behind (ie. each div is a SQL result).
In each DIV there's a Label, and also a "Like" HyperLink, listened by a "onclick" JS function that changes "Like" to "Dislike" text in LinkButton and triggers an AJAX call that calls MyMethod(userid, postid) method.
The MyMethod() method changes the Like/Dislike status for the user in SQL.
I want MyMethod() to update the Label too, so MyMethod() would do:
((Label)((Page)HttpContext.Current.Handler).FindControl("lbl_XX")).Text = "foo";
The problem is that i can't get any of the controls of the page.
I also tried a EventHandler added to the LinkButton, but eventually the MyMethod() never gets the Label by FindControl because Page object seems to come without controls.
How can i access the controls of the current page from a method?

Related

Asp.net Hidden field not having value in code behind, but *is* retaining value after postbacks

In my ASCX, I have an asp.net hidden field defined as <asp:HiddenField ID="hdnNewAsset" runat="server" />.
In the Code Behind I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
_service = new ArticleDataService(PortalId);
if (!IsPostBack)
{
string rawId = Request[ArticleQueryParams.ArticleId];
DisplayArticleDetails(rawId);
}
if (hdnNewAsset.Value.Trim() != string.Empty)
ProcessNewAsset();
}
Now, in my frontend, I have a javascript function to react to an event and set the hidden field and trigger a postback:
function assetSelected(assetGuid) {
$('input[id*="hdnNewAsset"]').val(assetGuid);
__doPostBack()
}
What's happening is that my hidden field is being set in the markup (chrome shows [
<input type=​"hidden" name=​"dnn$ctr466$Main$ctl00$hdnNewAsset" id=​"dnn_ctr466_Main_ctl00_hdnNewAsset" value=​"98d88e72-088c-40a4-9022-565a53dc33c4">​
] for $('input[id*="hdnNewAsset"]')).
However, when the postback occurs, hdnNewAsset.Value is an empty string.
What's even more puzzling is that at the beginning of Page_Load Request.Params["dnn$ctr466$Main$ctl00$hdnNewAsset"] shows 98d88e72-088c-40a4-9022-565a53dc33c4, and after the postback my hidden field has the same value (so the hidden field is persisting across postbacks), yet I cannot access this value via hdnNewAsset.Value.
Can anyone see what I"m doing wrong?
Ok I figured out the the issue.
The issue is that the code posted above was part of an ASCX user control. That user control was being loaded dynamically into an asp.net placeholder during the Page_Load event of the parent control.
Therefore, it seems that since both of these calls were in Page_Load of their respective calls, the inner control did not have it's values bound in the inner control's page_load. Modifying it so my inner control is loaded in Page_Init instead of Page_Load fixed all bindings.
Not sure if I wrote that in a way that makes sense to the general public.
Edit: It seems this part of the MSDN documentation is relevant to my issue:
If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

C# Dynamic UserControl, Button Click, and Master Pages

Got a very frustrating problem that I'm trying to solve regarding C#.NET's way of handling dynamically added usercontrols.
The basic rundown of my page setup is that I have an ASPX page which has a Master Page. The Master Page has some content placeholders. On the codebehind in the ASPX page, I call the Master.FindControl method to find the content placeholders, and then use the LoadControl method to load a UserControl into the placeholder.
On the UserControl, I have a series of textboxes, and a submit button. In this implementation, when I click on the submit button, and put a breakpoint into the OnClick event, I find that the OnClick event is never called.
However, if, instead of using this approach, I remove the Master Page, and add the content placeholders directly on the ASPX page, then use Placeholder.Controls.Add to add the UserControl instead of Master.FindControl, the button works perfectly.
Does anyone have any suggestions as to how I can resolve this without removing the Master Page?

how to target codebehind method using __DoPostBack without hidden control

I want to call a server side method using __DoPostBack, but i don't want a hidden ASP runat server control in my page. Is it possible to call a server side method by its name and not by the name of the control that triggers it?
The problem is, I have an asp button on my aspx page with onclick="ExportButton_Click", and when the button is clicked, it calls the ExportButton_Click codebehind (server side) method. My problem is, I want to get rid of the asp button, because I am trying to create a button dynamically, which when clicked, will do the same thing. Right now, my dynamically created button is calling the doPostBack javascript function which targets the asp Button which triggers ExportButton_Click. So... is it possible to call the ExportButton_Click codebehind method with __doPostBack, without having an asp button? Thanks in advance.
Pass the event target argument in to the __DoPostBack('myEvent') method, like that.
Then in your code-behind Page_Load(), have somewhere code like this:
if (Request.Form["__EVENTTARGET"] == "myEvent")
{
//call your button click function, and pass the button to it (can pass null as the EventArgs)
Button1_Click(Button1, null);
}
These two methods are your server-side friends:
this.Page.ClientScript.GetPostBackEventReference
this.Page.ClientScript.GetPostBackClientHyperlink
They can be used to generate javascript to link to your server side events.

To get controls inside static function

I am calling function in codebehind from javascript using webservice.
function GetAdmissionType()
{
InitComponents();
var type="";
type=document.getElementById(dlAdmissionType.id).value;
document.getElementById(hdnAdmissionType.id).value=document.getElementById(dlAdmissionType.id).value;
else if(type=="2")
{
InitComponents();
ViewResettingPanel()
makeFavorite(1);
}
}
function makeFavorite(id) {
PageMethods.SaveInfo(id, CallSuccess, CallFailed);
}
// This will be Called on success
function CallSuccess(res, id) {
alert(destCtrl);
}
// This will be Called on failure
function CallFailed(res) {
alert(res.get_message());
}
Following is my code in codebehind
[System.Web.Services.WebMethod]
public static void SaveInfo(String Id)
{
//to get textbox in form
}
Problem is iam not getting controls in aspx page in SaveInfo.Can anybody help to access controls in form inside saveinfo?
Static page methods cannot get the page's control tree. (They don't receive ViewState)
You will need to use an UpdatePanel.
You can make an asp:Button inside a <div style="display:none> with a regular Click event, make an UpdatePanel triggered by the button, and use Javascript to simulate a click of the button.
Alternatively, you could send the values of the controls that you need as parameters to your page method in Javascript. This will be more efficient than using an UpdatePanel.
You can't.
Your WebMethod is static, meaning it exists once, for all instances of your page class. It has no notion of any individual instance of your Page.
If you need to post your page back, you'll need to actually use postbacks, and not web service calls.

c# Ajax Lazy Loading

I need to populate 4 GridViews on an aspx page, but I only bind a datatable to one of them on page load. I need to pupulate the other 3 after page load.
does anyone know the best way to do this using ajax ?
Currently I'm using javascript to __doPostBack on a button that pupulates the 3 GridViews but unfortunately this forces a full page load even when using an update panel. I need the page to load, and then populate the GridViews as the datatables are returned.
any suggestions would be much apreciated.
The way you are doing it should work ok, although using jquery to populate a div via the $("#targetDiv").load("contentUrl"); function may be a cleaner way to do it. Anyway, in order to get your current implementation working, there could be a few things you want to look at:
I assume EnablePartialRendering is true on your ScriptManager (always worth checking!).
Make sure the eventTarget for the __dopostback call is set up as an async trigger for your update panels or that it is inside the UpdatePanel if you are only using one UpdatePanel. (See here for details)
Try returning false from the javascript code that executes in the onclick event handler if you have attached this to a button, to make sure the form is not being submitted normally by your browser when you click the button.
If I understand the question properly, you want the data to load after the page is in the browser. If this is the case, then you can fire an event with JavaScript when the page loads on the client.
One method I've used is to put a hidden (with CSS, not any property) button on the page and 'clicking' it with javascript. The event of the button click event will need to be wired in the page's code. Also the button would have to be in an update panel that either contains the grids you want to be bound or has the appropriate triggers to cause them to reload.
You might look at JQuery to get manage when this code gets fired. The $(document).ready(function(){ /* Your code here... */ }); method will fire after the entire DOM is available, which is faster than waiting on the entire page to load (images and so forth).

Categories

Resources