programmatically adding buttons and OnClientClick but still having post back issue - c#

I am trying to hide some divs using Javascript but i think the post back keeps reloading the page.
To make things more complicated my buttons are added programmatically by my code behind.
foreach (string line in thefilters)
{
Button newButton = new Button();
newButton.ID = Convert.ToString(line);
newButton.Text = Convert.ToString(line);
newButton.CssClass = "tblbutton";
//newButton.Attributes.Add("onclick", "hide_div("+newButton.ID+")");
newButton.OnClientClick = "return hide_div('" + newButton.ID + "')";
pnl_left.Controls.Add(newButton);
}
My javascript is located in the header as follows.
<script type="text/javascript">
function hide_div(filter) {
var pnl_right = document.getElementById("pnl_right");
var listofelements = pnl_right.getElementsById("div");
for (var i = 0; i < listofelements.length; i++) {
if (listofelements[i].id.indexOf(filter) == 0) {
document.getElementById(listofelements[i].id).style.display = 'inline';
}
else {
document.getElementById(listofelements[i].id).style.display = 'none';
}
}
return false;
}
I may have issues in the javascript for what i want to achieve but i am confident that if i can stop the postback then i can solve the javascript myself..
Thanks for any suggestions in advance.

You have not showed in which event you are adding controls. But I am assuming from your problem that you are doing this in Page_Load. If yes, try and move in OnInit event.
Second, in Page_Load you need to check
if(!IsPostBack)
{
//your code for adding controls
}
Hope that helps.

Related

Sometimes imagebutton click event not fired

I have a method that add's an onclick event too an imagebutton.
But sometimes you have to press the button multiple times before the "pop-up" window opens.
Any idea why this happens?
this is my code were I add the event to my imagebutton:
private void AddProjectDetails()
{
ImageButton imgBtn;
HiddenField hfld;
String ProjectNumber;
for (int i = 0; i < GridViewProperties.Rows.Count; i++)
{
hfld = GridViewProperties.Rows[i].FindControl("HiddenProjId") as HiddenField;
imgBtn = GridViewProperties.Rows[i].FindControl("ibtnShowExtra") as ImageButton;
ProjectNumber = hfld.Value;
imgBtn.Attributes.Add("onclick", "window.open('ProjectDetails.aspx?ProjectNumber=" + Server.UrlEncode(ProjectNumber) + "','Graph','height=590,width=600,left=50,top=50,scrollbars=yes'); return true;");
}
}
Try returning false from the javascript. This will prevent postback. Some times the postback can be faster then the windows.open, and in this case I don't think you want it.
Another solution is using an <a href='...' >image</a> instead of the imagebutton
Why are you using return true inside you java-script function.
Do you need postback on your page.
If not use return false.
I will also suggest you to write a javascript function and call it as follows
function OpenPopUp(projectNumber)
{
window.open("ProjectDetails.aspx?ProjectNumber="+ projectNumber
,'Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
return false;
};
and call it inside your c# code
imgBtn.Attributes.Add("onclick", "return OpenPopUp('"+Server.UrlEncode(ProjectNumber)+"');");
Like Stefano and Shekhar said, you must not use return true for LinkButtons, Imagebuttons, unless you want the page post back.
You can also use this way:
<asp:ImageButton ID="ButtonOpenProject" runat="server" ImageUrl="~/Images/OpenProject.png" OnClientClick="return OpenProject('"<%# ProjectNumber %>"');" />
And in your JavaScript script you do something like this:
function OpenProject(ProjectNumber){
window.open('ProjectDetails.aspx?ProjectNumber=' + ProjectNumber + ','Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
return false;
}
Hope this help.

ASp.net Button on jqueryui Dialog causes all from data to reset. UsesubmitBehavior=False, and databind in (!ispostback)

So I've been struggling with this for a couple days now. I have a login page, that checks if the user is logging in for the first time, and if so, it shows a jqueryui Dialog box asking the user to pick their security questions. The Dialog is simple, three dropdowns, three text boxes, and a continue and cancel button. The dialog is displaying find, and when you click continue, the data is saved to the database, but it only saves the default values of the dropdownlists, and it doesnt save the text from the text boxes. It seems to me like the form is posting back before the data saves, and then saves the blank/default content. I've tried everything I can find on the internet to fix this. As of right now, I'm launching the dialog box on page load for testing purposes. Code Below:
Javascript:
function validateQuestions() {
var q1Index = $('#<%= ddlQuest1.ClientID%>').get(0).selectedIndex;
var q2Index = $('#<%= ddlQuest2.ClientID%>').get(0).selectedIndex;
var q3Index = $('#<%= ddlQuest3.ClientID%>').get(0).selectedIndex;
"<%=Q3Index%>" = q3Index;
var label = document.getElementById('<%= _lblQuestError.ClientID%>');
label.style.display = 'none';
if (q1Index == q2Index || q1Index == q3Index || q2Index == q3Index) {label.style.display = 'block';}
else {label.style.display = 'none'}
return false;
}
function validateAnswers() {
var ans1Text = $('#<%= txtAnswer1.ClientID%>').val();
var ans2Text = $('#<%= txtAnswer2.ClientID%>').val();
var ans3Text = $('#<%= txtAnswer3.ClientID%>').val();
var ans1error = document.getElementById('<%= _lblAns1Error.ClientID%>');
var ans2error = document.getElementById('<%= _lblAns2Error.ClientID%>');
var ans3error = document.getElementById('<%= _lblAns3Error.ClientID%>');
ans1error.style.display = 'none';
ans2error.style.display = 'none';
ans3error.style.display = 'none';
if(ans1Text=""){ans1error.style.display = 'block';}
else if(ans2Text=""){ans2error.style.display = 'block';}
else if(ans3Text=""){ans3error.style.display = 'block';}
else { ans1error.style.display = 'none'; ans2error.style.display = 'none'; ans3error.style.display = 'none'}
return false;
}
function cancel() {
$("#_dlgQuest").dialog('close');
return false;
}
function showDialog() {
var secQuestDlg = $('#_dlgQuest').dialog({
bgiframe: true,
height: 350,
width: 900,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: ".8"
}
});
secQuestDlg.parent().appendTo('/html/body/form[0]');
}
Button aspx: <asp:Button ID="_dlgbtnContinue" ToolTip="Continue" runat="server" Text="Continue"
UseSubmitBehavior="false" OnClick="_dlgbtnContinue_Click" CausesValidation="false" />
PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlQuest3.Attributes.Add("onchange", "javascript:validateQuestions();");
ddlQuest1.Attributes.Add("onchange", "javascript:validateQuestions();");
ddlQuest2.Attributes.Add("onchange", "javascript:validateQuestions();");
txtAnswer1.Attributes.Add("onblur", "javascript:validateAnswers();");
txtAnswer2.Attributes.Add("onblur", "javascript:validateAnswers();");
txtAnswer3.Attributes.Add("onblur", "javascript:validateAnswers();");
List<String> lstQuestions = QuikDrawServiceHelper._QuikDrawClient.GetQuestions();
ddlCountry.Focus();
FillQuestions();
ClientScript.RegisterStartupScript(GetType(), "hwa", "showDialog()", true);
}
}
Fillquestions:
try
{
foreach (string s in lstQuestions)
{
if (s.Equals(Customer.Quest1Code))
{
q1 = s;
}
if (s.Equals(Customer.Quest2Code))
{
q2 = s;
}
if (s.Equals(Customer.Quest3Code))
{
q3 = s;
}
}
}
catch (Exception ex)
{
}
Complete Click Event:
protected void _dlgbtnContinue_Click(object sender, EventArgs e)
{
Customer = CompanyServiceHelper._CompanyClient.GetCustomerByID(Convert.ToInt32(Session["CustomerID"].ToString()));
if (Session["FirstLogin"] == "Yes")
{
Customer.Quest1Code = ddlQuest1.SelectedValue;
Customer.Quest1Ans = txtAnswer1.Text;
Customer.Quest2Code = ddlQuest2.SelectedValue;
Customer.Quest2Ans = txtAnswer2.Text;
Customer.Quest3Code = ddlQuest3.SelectedValue;
Customer.Quest3Ans = txtAnswer3.Text;
CompanyServiceHelper._CompanyClient.AddQuestionsForCustomer(Customer);
Session["FirstLogin"] = "Yes";
Session["CustID"] = Customer.CustID;
}
I've tried linkbuttons as well, and i get the same thing. Any help would be greatly appreciated.
The root cause of the problem you are facing is the fact that the dialog is made "display:none" when popup disappears, and this resets all the values inside the dialog, making them not accessible on server. Despite "runat=server", form fields are not accessible on server bcz of "display:none", making you think the values are never set !!
Seems like when you click the dlgbtnContinue button it is still not doing a postback, therefore you get the !isPostBack all over, and then resets the values. After this, the _dlgbtnContinue_Click event is getting triggered, saving the blank values. Maybe try to check in !isPostBack if also the values in the DropDown are not the default, meaning that if they are not the default values you do not want to get inside that if again. Just an idea... It would be good to have the _dlgbtnContinue_Click code. Good luck.

How To set Default Button for ENTER key

We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.

Redirect via datagridView

I am currently working in ASP.Net / C#. I am trying to make the server redirect to another page using via the rows in a datagrid, however, my code doesn't seem
to work. Any help would be appreciated.
protected void GridView1_RowCreated()
{
foreach (GridViewRow row in GridView1.Rows)
{
Color color = row.BackColor;
string color2 = System.Drawing.ColorTranslator.ToHtml(color);
Session["" + row.Cells[0].Text + ""] = row.Cells[0].Text;
//row.Attributes.Add("onclick", "zz(); return false;");
/*if (row.RowState == DataControlRowState.Alternate)
{
row.Attributes.Add("onclick", "redirectFunction(); return false;");
//row.Attributes.Add("onmouseover", "this.style.backgroundColor=' #FFFFFF';");
//row.Attributes.Add("onmouseout", "this.style.backgroundColor='" + color2 + "';");
//row.Attributes.Add("onclick", cookie.Value = row. GridView1.SelectedRow.Cells[0].Text);
//row.Attributes.Add("onclick", "zz(); return false;");
}
else
{
//row.Attributes.Add("onmouseover", "this.style.backgroundColor=' #FFFFFF';");
//row.Attributes.Add("onmouseout", "this.style.backgroundColor='" + color2 + "';");
//row.Attributes.Add("onclick", "zz(); return false;");
}*/
}
}
public void redirectFunction()
{
Response.RedirectPermanent("View.aspx");
}
Other page
if(Session["session"].ToString() != null)
{
// do something
}
It looks like you are adding a client side on click event and then trying to call a c# method which won't work.
This code:
foreach (GridViewRow row in GridView1.Rows)
{
row.Attributes.Add("onclick", "redirectFunction()");
// Or if you want to pas in an id
row.Attributes.Add("onclick", "redirectFunction(" + rowId + ")");
}
is adding a javascript click event to the row and you are telling it to call a javascript method. You then need to add the javascript method to your aspx page:
<script type="text/javascript">
function redirectFunction() {
alert("do you see this??");
window.location = "View.aspx";
}
</script>
I have added an alert statement, you can get rid of it but do you see this popup? If not check for any javascript errors on the page.
You could also do this with jQuery (it's much easier):
$('.yourrowclassname).click(function () {
window.location = "View.aspx";
});
This means you do don't need to add the attribute in code, just use/add a class to the row.
You should implement this feature by using the SelectedIndexChanged event for the GridView. From there, you can grab all the properties and information of your object that you will need to display in your View.aspx page.
Check this post here, this will help you achieve what you are trying to do
https://stackoverflow.com/a/331662/125551
just add session["var"]= val or send that value in url and get that value in page_load on other page from querystring instead of session

Javascript is not called on radiobutton list index change

I have written code for javascript but it is not called any how. I tried to call both form html side and also by assigning attribute from page load event but it is not at all called.
This is the code for my javascript.
function rdbantiplatelet_onClick(thiscontrol, trName) {
alert('hi');
var RB1 = thiscontrol;
var radio = RB1.getElementsByTagName("input");
var trDose = document.getElementById(trName.toString());
// var RB1 = document.getElementById("<%=this.rdbantiplatelet.ClientID%>");
// var radio = RB1.getElementsByTagName("input");
// var tblAntiplatelet = document.getElementById("<%=tblAntiplatelet.ClientID %>");
for (var i = 0; i < radio.length; i++){
if (radio[i].checked){
trDose.style.display = "";
return true;
}
else{
trDose.style.display = "none";
return true;
}
}
return false;
}
This is the code to call javascript written in page_load event..
rdbantiplatelet.Attributes.Add("OnClick", "return rdbantiplatelet_onClick(this,'" + trDose.ClientID.ToString() + "');");
Try an alert() first to make sure your onclick is firing, then try your rdbantiplatelet_onClick() function:
rdbantiplatelet.Attributes.Add("OnClick", "alert('I am working');");
First of all for your reference here is a list of standard html events
http://www.w3schools.com/tags/ref_eventattributes.asp
try adding something like this to the html radiobutton element
onchange="alert('on change fired');"
and
onclick="alert(' on click fired');
so you can make sure you are picking up the right event.
Once you have the right event then replace the alert call to your method
which would be something like this
onchange="rdbantiplatelet_onClick(this, this.parent.id)"
...you might have to change the 'this.parent.id'
Make sure you are running through a good web browser for development FireFox with the firebug plug-in is great for this stuff.
You are add click event to html table that holds radiobuttons. Use script below:
foreach (ListItem item in rdbantiplatelet.Items)
{
item.Attributes.Add("onclick", "return foobar(this);");
}

Categories

Resources