I have a class derived from WebControls.TableCell.
When the Text property is set, I call a method that dynamically adds asp:Panels and asp:LiteralControls to the Cell. I want to reference these controls in Javascript, so naturally I tried using the ClientId of the panels in my JS functions. However, these controls have no ClientId set (the string is empty). Why is this? How do I force the ClientIds to be set?
As a temporary solution, I set the ClientIDMode to "static" and created the IDs on my own, but this is not satisfactory because it's hard to reference those IDs in JS. Why? If you assign, for example, "12345" to one control, it gets changed on client side to something like "MainContent_123456". This is bad because the "MainContent" part is not fixed; thus I never know for sure what the real Id on the client side will be. Currently, I can get the control with jQuery using $ctrl = $('[id$='12345']');, but this is dirty because it would get any control that has '123456' in its id.
So, back to the original question: how do I get my ClientIds set automatically for my panels in my custom TableCells?
Edit: Code added
protected void Page_Load(object sender, EventArgs e)
{
this.ClientIDMode = System.Web.UI.ClientIDMode.Static;
}
Code in the method that adds the controls to the custom TableCell:
Panel remainingTextPanel = new Panel();
remainingTextPanel.ID = Guid.NewGuid().ToString();
remainingTextPanel.Style["display"] = "none";
LiteralControl remainingText = new LiteralControl(myText.Substring(initialStringLength, myText.Length - initialStringLength));
remainingTextPanel.Controls.Add(remainingText);
this.Controls.Add(remainingTextPanel);
Panel linkBtnPanel = new Panel();
LinkButton lnkBtn = new LinkButton() {Text = "...", OnClientClick = "toggleDynamicText('" + remainingTextPanel.ID + "'); return false;" };
lnkBtn.Font.Bold = true;
linkBtnPanel.Controls.Add(lnkBtn);
this.Controls.Add(linkBtnPanel);
And the JS Code:
function toggleDynamicText(id) {
$ctrl = $('[id$=' + id + ']');
$(document).ready(function () {
$ctrl.toggle(1000);
});
}
Without seeing any code it's difficult to say what's going on but to access your controls using jQuery you can do the following:
$("#<%=myElement.ClientID%>")
This way it doesn't matter what .NET assigns as the ID.
Related
ASP.NET 4.7.2 Web Forms c# VS 2019
I am trying to use a modalpopupextender to prompt for new data for foreign key fields. Like the form itself, the MPE is built on the fly in code -- in this case the click handler for the hidden button that the Javascript fires off to build and show the MPE.
I read every single article on SO and the ASP forums and tried everything I saw there. No joy. I get the popup perfectly. Hitting OK closes the popup, but never fires the OK Event.
Here is the code:
//Building the form, we do this in OnInit:
// AJAX Update Panel
UpdatePanel PUP = new UpdatePanel()
{
ID = "PUP",
};
PlaceHolder.Controls.Add(PUP);
// HiddenField containing the field name to permit
// creating the correct modalpopup.
HiddenField HFPopupField = new HiddenField()
{
ID = "HF_POPUP"
};
PUP.ContentTemplateContainer.Controls.Add(HFPopupField);
// Create Hidden button to track the popup
Button BPopup = new Button()
{
ID = "BPOPUP",
UseSubmitBehavior = false
};
BPopup.Click += BPopup_Click;
BPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(BPopup);
// And create the background panel for the popup.
Panel PnlPopup = new Panel()
{
ID = "PNLPOPUP",
CssClass = "MpeBackground"
};
PnlPopup.Attributes.Add("style", "display: none;");
PUP.ContentTemplateContainer.Controls.Add(PnlPopup);
/// Event handler for hidden button.
protected void BPopup_Click(object sender, EventArgs e)
{
[snip -- code to get the dataset that is being filled]
UpdatePanel PUP = Placeholder.FindControlRecursive("PUP");
Table T = new Table()
{
CssClass = "PopupTbl"
};
TableRow TRTitle = new TableRow();
TableCell TCTitle = new TableCell()
{
CssClass = "PopupTitle",
ColumnSpan = 2
};
Label LPopTitle = new Label()
{
Text = [title of the popup]
};
TCTitle.Controls.Add(LPopTitle);
TRTitle.Cells.Add(TCTitle);
DataRow drData = null;
// Add Fields, and also the cancel and Add buttons
foreach (DataColumn DC in dsColumns.Tables[0].Columns)
{
TableRow TRColumn = [create a tablerow with 2 columns, a prompt and the input field]
if (TRColumn != null)
{
T.Rows.Add(TRColumn);
[snip]
}
} // end of foreach(DataColumn DC in dsColumns.Tables[0].Columns)
PnlWindow.Controls.Add(T);
TableRow TRButtons = new TableRow();
TableCell TCButtons = new TableCell()
{
ColumnSpan = 2,
CssClass="PopupButtons"
};
Button MPEBOK = new Button()
{
ID = "MPE" + sFieldName + "_MPEBOK",
Text = "OK",
CausesValidation = false,
UseSubmitBehavior = false
};
MPEBOK.Click += MPEBOK_Clicked;
TCButtons.Controls.Add(MPEBOK);
LiteralControl LCB = new LiteralControl()
{
Text = " "
};
TCButtons.Controls.Add(LCB);
//************************************************************
//*** Postback Trigger ***
//************************************************************
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger()
{
ControlID = MPEBOK.ID,
EventName = "click"
};
PUP.Triggers.Add(trigger);
//************************************************************
//*** Cancel Button ***
//************************************************************
Button MPEBuhBye = new Button()
{
ID = "MPE" + sFieldName + "_BUHBYE",
Text = "Cancel",
UseSubmitBehavior = false
};
TCButtons.Controls.Add(MPEBuhBye);
TRButtons.Cells.Add(TCButtons);
T.Rows.Add(TRButtons);
PnlPopup.Controls.Add(PnlWindow);
AjaxControlToolkit.ModalPopupExtender MPE = new AjaxControlToolkit.ModalPopupExtender()
{
ID = "MPE" + sFieldName,
PopupControlID = "PNLPOPUP",
TargetControlID = "BPOPUP",
BackgroundCssClass = "MpeBackground"
};
// Add the MPE to the UpdatePanel.
PUP.ContentTemplateContainer.Controls.Add(MPE);
// Show the modal popup extender.
MPE.Show();
}
protected void MPEBOK_Clicked(object sender, EventArgs e)
{
[snip - this never fires]
}
I cannot find out what is happening here. Can anyone see something hinky?
Thanks
John.
You can't add a server side button or inject a server side button into the page DOM.
When you drag a asp.net button onto the form, BOTH the "mypage.cs" and mypage.desinger.cs ARE updated. The wire up of the button occurs at design time, and you would have to modify mypage.desinger.cs ALSO and ADD a button event stub.
So you can't do this.
A compromise would be to also add some js and have that HTML button execute a .click() method of a hidden asp.net button you drop into that page (that would give you the post back, and the running behind of a separate button event code stub.
This event resolution occurs at compile time - not at page render time. You have to drop that button onto the page.
I suppose you could adopt a standard that you always place right below that "div" on the page the button (hidden with style=none. And then as noted, have your injected code along with some js execute a click on the hidden button. Or just have the js button code execute a __doPostback("some value") and pick this up in the page on-load event, and then call the routine (function) from on-page load event.
I think better would be to use a jQuery.UI dialog, as that dialog CAN say load + use another different web page into a “div” on the existing page. So you layout, make, and create the nice looking popup form as a separate web page. jQuery is able to remove the “form” and additonal tags out of that page load, and then inject it into the existing page. (that code would be rather hard to re-produce). so jQuery.UI is able to pop up that separate page. however, the buttons on that loaded page (into that div) of course can't really run any code behind in the current page. However, the buttons CAN run local js in the current page. Thus the actions of this injected page would be local to each page. But the popup would not be directly calling a code behind stub.
Now, to adopt jQuery.UI, then you also have to of course adopt jQuery. So that is two extra libraries you need. (but, jQuery you likely already have).
However, I suppose the whole point of using the ajax toolkit is to avoid jQuery.ui in the first place. To be fair, before jQuery.ui came along, that tool kit was REALLY impressive, and gave asp.net folks a REAL leg up on the competition. (and it tends to be MUCH less wiring up then say using jQuery.UI
So the AjaxToolkit in its heyday was impressive. Now, it of course showing its age, but I still use the kit, and this is especially the case for the AjaxFileUploader. And yes I do use the popups – even to this day. However, I find now that jQuery.UI dialogs are more flexible, and would be better in this case (because you want a on-the fly setup).
Also, having code behind buttons in even the jQuery.UI dialog, or in this case the ajax popup? Well, only the action button can run code behind. The cancel button of course will just dismiss the dialog. However, any button in the dialog that WILL run code behind? Well, that's ok, since you have a page post back, and it actually the page postback that BLOWS out the dialog anyway.
I have been working with Web Forms for a short while now and I have read most of what I have found about this on google. However, I am still unclear on how to work with this properly. I like the picture in this answer, but find it a bit too generic. I have not found one decent, concrete example on how to work with these events.
I am currently creating several controls dynamically in code behind in the Page_Load event:
foreach (Service service in Services)
{
// service div
HtmlGenericControl serviceDiv = new HtmlGenericControl("div");
serviceDiv.ID = service.ID;
serviceDiv.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
outerDiv.Controls.Add(serviceDiv); //outerDiv exists in the aspx page
// service updatepanel
UpdatePanel uPanel = new UpdatePanel()
{
ID = service.ID + "_uPanel",
UpdateMode = UpdatePanelUpdateMode.Conditional
};
serviceDiv.Controls.Add(uPanel);
// status span
HtmlGenericControl statusSpan = new HtmlGenericControl("span");
statusSpan.ID = service.ID + "_statusSpan";
statusSpan.InnerHtml = service.Status;
uPanel.ContentTemplateContainer.Controls.Add(statusSpan);
// show specific content
if (service.Status.Equals(ServiceControllerStatus.Running.ToString()))
{
// status color
statusSpan.Attributes.Add("class", "status-run");
// stop button
HtmlButton stopButton = new HtmlButton();
stopButton.ID = service.ID + "_btnStop";
stopButton.InnerHtml = "<i class=\"fa fa-stop btn-red\"/></i>";
stopButton.Attributes.Add("type", "button");
stopButton.Attributes.Add("runat", "server");
stopButton.Attributes.Add("class", "btn btn-link btn-xs");
stopButton.Attributes.Add("title", "Stop");
stopButton.ServerClick += new EventHandler(BtnStop_Click);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(stopButton);
uPanel.ContentTemplateContainer.Controls.Add(stopButton);
// restart button
HtmlButton restartButton = new HtmlButton();
restartButton.ID = service.ID + "_btnRestart";
restartButton.InnerHtml = "<i class=\"fa fa-refresh btn-blue\"/></i>";
restartButton.Attributes.Add("type", "button");
restartButton.Attributes.Add("runat", "server");
restartButton.Attributes.Add("class", "btn btn-link btn-xs");
restartButton.Attributes.Add("title", "Restart");
restartButton.ServerClick += new EventHandler(BtnRestart_Click);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(restartButton);
uPanel.ContentTemplateContainer.Controls.Add(restartButton);
}
else
{
// status color
statusSpan.Attributes.Add("class", "status-stop");
// start button
HtmlButton startButton = new HtmlButton();
startButton.ID = service.ID + "_btnStart";
startButton.InnerHtml = "<i class=\"fa fa-play btn-green\"/></i>";
startButton.Attributes.Add("type", "button");
startButton.Attributes.Add("runat", "server");
startButton.Attributes.Add("class", "btn btn-link btn-xs");
startButton.Attributes.Add("title", "Start");
startButton.ServerClick += new EventHandler(BtnStart_Click);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(startButton);
uPanel.ContentTemplateContainer.Controls.Add(startButton);
}
// version span
HtmlGenericControl versionSpan = new HtmlGenericControl("span");
versionSpan.ID = service.ID + "_version";
versionSpan.InnerHtml = service.Version;
versionSpan.Attributes.Add("class", "version-text");
serviceDiv.Controls.Add(versionSpan);
What would I gain from creating these in Page_Init? If I create them in Page_Init, how do I access them in Page_Load? Private global lists of UpdatePanels and HtmlButtons feels so unclean.
I know that the ViewState loads between Page_Init and Page_Load, but what does that really mean? Since I don't do full postbacks, but instead use RegisterAsyncPostBackControl to only update the UpdatePanel's on postback, don't I need to re-populate in Page_Load?
If you don't need the ViewState, then you can also create the controls in Page_Load. The ViewState is used to store the values of the controls (which ones depends on the control) and to use them when the PostBack is sent to the server.
For instance, if you have a textbox, the PostBack contains the new value of the textbox and also the old value in the ViewState. The ASP.NET framework now compares those two and raises the TextChanged event if necessary. Without ViewState, this would not be possible.
The best advice you can give regarding dynamically created controls in ASP.NET WebForms is to avoid using them. They increase complexity very fast und are usually not necessary (even if it seems so at first).
In the majority of the cases, there is a much simpler approach, e.g. by using a Repeater. In your case, you have a list of services. You can bind this list to a Repeater and by that avoid to create the controls manually. See this link on how to use a Repeater.
Another upside of using a Repeater is that you can define the UI in the ASPX markup instead of in the code behind file. In your example, you change the UI based upon the status of the service. In this case, using the ItemDataBound-event of the Repeater might be a good option.
I have ASP.Net application that have multiple User Controls in the same page every one have its hidden field that holds a value, and every one have button that calls pop-up and through this value from hidden field to it.
The problem that when i try to access the hidden field and get the value inside , the program always get the last one (which created last).
How can i get the value of the inner hidden field in the current UserControl (Which i'm clicking the button from)?
Attempts:
var hdnRegion = "<%=hdnRegionId.ClientID%>";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
another one:
var currentControl = "<%=this.ClientID%>";
var hdnRegion = currentControl + "_" + "hdnRegionId";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
I also tried to call a property from code behind that returns the value and one that returns the whole control with no correct result.
Any suggestions would be appreciated...
Accourding to your comment under the question, your btnUpdate and hdnRegionId controls are in the same container (for instance in the same div) so try this:
$('input[id*="btnUpdate"]').click(function(){
var regionIdVal = $(this).parent().children('input[id*="hdnRegionId"]').val();
methodName(regionIdVal);
});
This is a JSFiddle Demo that simulate your HTML code that is rendered by ASP.NET.
I have one image button in the custom control like below.
public string SearchTableName = string.Empty;
public string SearchColumnName = string.Empty;
public string SiteURL = string.Empty;
ImageButton _imgbtn;
protected override void OnInit(EventArgs e)
{
_imgbtn = new ImageButton();
_imgbtn.ImageUrl = ImageURL;
_imgbtn.OnClientClick = "ShowSearchBox('" + SiteURL +"/_layouts/CustomSearch/SearchPage/Searchpage.aspx?table_name=" + SearchTableName + " &column_name=" + SearchColumnName + "')";
}
On Clicking of the image button I want to migrate to the another window which is a popup. For this I written a javascript function. I am setting the SearchTableName and SearchColumnName in the web page in which we are consuming this custom control like below. Before consuming I registered this control in web page with register tag.
<ncc:SearchControl runat="server" ID="txtSearchControl" /> In code behind file of this webpage I am using following code to set the values.
protected void Page_Load(object sender, EventArgs e)
{
txtSearchControl.ImageURL = "_layouts/Images/settingsicon.gif";
txtSearchControl.SearchTableName = "Employees";
txtSearchControl.SearchColumnName = "LastName";
txtSearchControl.SiteURL = "http://Sp2010:8787";
}
Now coming to the problem, when I click the image button the SearchTableName and SearchColumnName values are not coming. I think I am calling OnClientClick function, thats why the values are not being set. But how to set the values for the custom control based on the values setting in the webpage. If I use the Click function will it serve my purpose? If so, how to call that javascript function from this click event.
Finally got solution. I am initializing the values in the page init method in the custom control. Thats why the values i am setting in the visual webpart page are not being captured. Now I changed the initializing the values in CreateChildControl method. Now it works perfectly. Thank you.
I write script like this in my .cs file :
StringBuilder script = new StringBuilder();
script.Append("<script type=\"text/javascript\"> function submitform(){");
script.Append(" document.forms['" + ((HtmlGenericControl)frm).Attributes["id"] + "'].submit();} </");
script.Append("script>");
How can i call this function in the OnClientClick of my link button ?
LinkButton hl_process = new LinkButton();
hl_process.OnClientClick = ""
Edit1:
protected Control CreateCommForm()
{
HtmlGenericControl frm = new HtmlGenericControl("form");
frm.Attributes.Add("id", "sal");
frm.Attributes.Add("method", "post");
frm.Attributes.Add("action", "https://------");
/////////////////////////////////////////
HtmlGenericControl hdn_sal_a = new HtmlGenericControl("input");
hdn_sal_a.Attributes.Add("id", "hdn_sal_a");
hdn_sal_a.Attributes.Add("name", "hdn_sal_a");
hdn_sal_a.Attributes.Add("type", "hidden");
hdn_sal_a.Attributes.Add("value", Session["emp_num"].ToString());
/////////////////////////////////////////
HtmlGenericControl hdn_sal_b = new HtmlGenericControl("input");
hdn_sal_b.Attributes.Add("id", "hdn_sal_b");
hdn_sal_b.Attributes.Add("name", "hdn_sal_b");
hdn_sal_b.Attributes.Add("type", "hidden");
hdn_sal_b.Attributes.Add("value", Session["user_name"].ToString());
frm.Controls.Add(hdn_sal_a);
frm.Controls.Add(hdn_sal_b);
column1.Controls.Add(frm);
return frm;
}
separate the concerns The Visual part your application shouldn't be affected if you move your app to java or ruby. that's what separate of concerns is.
write the client script in the client, not in the cs file:
$('#<%= hl_process.ClientID %>').click(function(){
...
$('#formId').submit();
// if the button inside the form:
this.form.submit(); // HTML5
// Or:
$(this).closest('form').submit();
// if the button not inside the form :
var class = $(this).attr('class');
$('form.' + class).submit();
});
Use jquery to bind to the click event instead of doing this on the server side:
Submit Me
then in javascript something like:
<script type="text/javascript">
$('.blah').click(function() {
document.forms[0].submit();
});
</script>
Edit:
While you can generate UI elements with codebehind it's not quite the asp.net way. Use repeaters if you must repeat the generation of controls. Actually, creating multiple forms is not the asp.net way either, as it assumes only one form running at the server context and everything else binds to an event on submission. Anyways, it seems you're still learning asp.net and probably coming form PHP or something similar.
To accommodate your request, I'd advice to stay away from from generating JS on the server side. Give different class names to your forms and use the same method above. You don't need a LinkButton to submit the form, a simple anchor <a> fits the bill.
You can use the ClientID property (if you don't use classes), but you must first attach the parent control to the page for the algorithm to kick in.
So, your code would be something like:
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["onclick"] = "$('#" + frm.ClientID + "').submit();";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
The alternative way (better separation of concerns)
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["class"] = "submitter";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
And in javascript we find the parent form and submit it (this can be in a static js file):
<script type="text/javascript">
$('.submitter').click(function(
$(this).parents('form').submit();
));
</script>