How to enable a disabled button in code behind in asp.net - c#

I have disabled a button in javascript. On page load I need to enable it again.
This is my code in script.
$(document).ready(
function () {
document.getElementById("<%=btnsubmit.ClientID%>").disabled = true;
});
In code behind,I am enabling it
protected void Page_Load(object sender, EventArgs e)
{
btnsubmit.Enabled = true;
}
but its not enabled.
Can anyone please help?

The server side event Page_Load always run first..So you are enabling the button first and then disabling it in the clientside $(document).ready..
I don't know what is your goal.But you can solve the problem by..
protected void Page_Load(object sender, EventArgs e)
{
btnsubmit.Enabled = false;
}
Javascript..
$(document).ready(
function () {
document.getElementById("<%=btnsubmit.ClientID%>").disabled = false;
});
Refer this link for extra reading...

Try with btnsubmit.disabled = false;
like
protected void Page_Load(object sender, EventArgs e)
{
btnsubmit.disabled = false;
}

Page load runs when the page is rendered on the server - First.
After the page gets rendered on the server it gets to the client and then the js starts running.
Your page load assignment gets overridden on the clients end.
You can do both on the server(enable\disable).
delete this:
$(document).ready(
function () {
document.getElementById("<%=btnsubmit.ClientID%>").disabled = true;
});
And use this:
protected void Page_Load(object sender, EventArgs e)
{
if(blah blah blah)
btnsubmit.Enabled = true;
else
btnsubmit.Enabled = false;
}

try this out , using jQuery
$(document).ready(function(){
$('#buttonID/.buttonClass').removeAttr('disabled');
});
and through javascript use
document.getElementById("buttonid").setAttribute("disabled", false);

You can use asp button in front end. And choose enable false to disabled it.
<asp:Button id="btnName" runat="server" Text="Add" Enabled="false"/>
Then you can enable it in server side.
btnName.Enabled = true;

Related

How to prevent back button after LOGIN in asp.net?

I have 2 pages home.aspx and admin.aspx
After successfully logging into admin.aspx when i click back button of browser, it does redirect to home.aspx but that i don't want.
I am checking session variable persistence on home.aspx but for some reason its not working!!
Here's the code
home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] != null)//should work as session will not be null!
{
Response.Redirect("admin.aspx");
}
} //.....some code..after this
if (dt.Rows.Count != 0)
{
Session["aname"] = TextBox11.Text;
Response.Redirect("admin.aspx");
}
admin.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] == null)
{
Response.Redirect("home.aspx");
}
} //some code after this..
protected void logoutbutton_Click(object sender, EventArgs e)
{
Session["aname"] = null;
Session.Abandon();
Session.Clear();
Response.Redirect("home.aspx");
}
NOTE:(things working fine)
1.login working sucessfully
2.logout working sucessfully
3.back button is disabled once loggedout(not going on admin.aspx)
Issue:
When logged in i.e. on admin.aspx ,on clicking back button it redirects to home.aspx which i don't want. i expect it to remain on same admin.aspx
ok.. finally trying all your solutions..this code worked on adding in my masterpage (in head tags)
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
full details on this page
You can push the Window History forward to prevent the back button. This has work for me in most cases. Include this JavaScript on your Admin.aspx page.
$(function() {
window.history.forward();
});

How does the Post back get reset ?

Let me elaborate on this... I have the code below, there is a Page_Init (which I still don't understand why it fires more than once, but that is another story), and a Page_Load and I am checking for the "isPostBack" ... everything works great while I use my controls, radio button and drop down list, as well as Buttons; however, if I press the key, even accidentally, the "isPostBack" is reset to False. What am I doing wrong? Also, my AutoEventWireup="true".
Also, this is an .ascx file.
protected void Page_init(object sender, EventArgs e)
{
LoadPageText1();
paymntpnl1.Visible = true;
curbalpnl.Visible = false;
paymntpnl2.Visible = false;
paymntpnl3.Visible = false;
paymntpnlcc.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
LoadPageData();
getContractInfo();
step2lbl.BackColor = System.Drawing.Color.White;
nopmt = Convert.ToDecimal(numpmts.Text);
nopmt = nopmt * nopymts2;
sb.Clear();
sb.Append("$");
sb.Append(nopmt.ToString("#.00"));
nopymts.Text = sb.ToString();
ValidateCC();
chkNewCC();
bool crdcrd = credCard;
bool newcrd = nwCard;
if (!IsPostBack){
}
}
You're checking IsPostBack but you're still doing all the resetting before the check! And then the check makes no difference because it's an empty conditional block! You should be doing this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// All the initial setup that you don't want to do again goes here.
}
// All the stuff you want to do on first load AND PostBack goes here.
}
Make sure you understand how conditionals work.

when I every refresh page load button_click events run too

I have code Page_Load and btnGonder_Click.I records the some data to database when I click the btnGonder.And I get and show data in the datalist the code which inside the page_load.The problem is that When I every refresh the page,it runs btn_Gonder_Click events and so it records the same data to database.my code is below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Cevap cevaplar = new Cevap();
int soru_id = Convert.ToInt32(Request.QueryString["Soru_Id"]);
cevaplar.soru_id = soru_id;
DataTable dtcvp = new DataTable();
dtcvp = cevaplar.Cevaplarive_CevapVerenleri_Getir();
datalistcevaplar.DataSource = dtcvp;
datalistcevaplar.DataBind();
}
}
protected void btnGonder_Click(object sender, EventArgs e)
{
Users kullanicim = new Users();
HttpCookie bilgiler = Request.Cookies["Kullanicicookie"];
kullanicim.mail = bilgiler["mail"];
int donenkullaniciid = kullanicim.Kullanici_Id_Donder();
cevaplar.cvpveren_id = donenkullaniciid;
Sorular sorular = new Sorular();
sorular.Cevap_Sayisi_Artir(soru_id);
bool durum = cevaplar.Cevap_Ekle();
if (durum)
{
lblDurum.Text = "Cevabınız Eklenmiştir";
}
else
{
lblDurum.Text = "Cevabınız Eklenmemiştir";
}
DataTable dtcvp = new DataTable();
dtcvp = cevaplar.Cevaplarive_CevapVerenleri_Getir();
datalistcevaplar.DataSource = dtcvp;
datalistcevaplar.DataBind();
}
Page refresh re-fires the same event which has caused the previous postback , so if you refresh the page after clicking the button then button click event will fire. Now to avoid that you have gor multiple solutions. see here
Use this.IsPostBack inside btnGonder_Click() to check the status of submission and return
If you don't want to resubmit the page on refresh then from btnGonder_Click you need to redirect to the same page instead of directly binding data. As this is the basic problem with the Asp.net application.
Do Response.Redirect and pass the name of the page.
If you have already clicked on a button which caused a post back. Next onwards pressing F5, the browser will ask you RESEND which means click the button again. This is normal browser behaviour
Basically you need a workaround to check if it is a page refresh or an actual button click. You can do as below:
The key here is ViewState["IsPageRefresh"] & Session["IsPageRefresh"]. Note that ViewState needs to be enabled on the page for this to work; if ViewState is not enabled then a hidden field may be used.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["IsPageRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["IsPageRefresh"] = Session["IsPageRefresh"];
}
protected void btnPost_Click(object sender, EventArgs e)
{
if (Session["IsPageRefresh"].ToString() == ViewState["IsPageRefresh"].ToString())
{
//Put your database INSERT code here
Session["IsPageRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}
One simple trick but may be not a standard practice I too agree is below:
Don’t disable the button in the server side. After the page has finished loading the button works as usual.
<head runat="server">
<title></title>
<script type="text/javascript">
function checkButton() {
var btn = document.getElementById("btnGonder");
btn.disabled = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGonder" runat="server" onclick="btnGonder_Click"
OnClientClick="checkButton();" />
</div>
</form>
</body>

Run a javascript on postback in c#

I used the below manner to run a JavaScript upon postback and it worked fine for me.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'hidden';</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>function show()</script>");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'visible';</script>");
}
}
The above code worked fine and now I want to try something like below.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"verify","<script type='text/javascript'>verify1();</script>");
}
else
{
}
}
in the above code verify1() is a JavaScript linked externally to ASPX page. I am unable to execute verify1() function using this code. And verify1() function works fine when placed as <body onload="verify1();"> Is there any syntax error(s) in my above code?
this may help you,
Page.ClientScript.RegisterStartupScript(this.GetType(), "verify", "verify1()", true);
Maybe that script is being executed before verify1()'s function definition. By the time body.onload fires, the main page has completed parsing and all external scripts have been loaded, which is why it works in that scenario.
Can you use jquery? One option is to use jQuery's onload functionality, which won't be executed until everything is intialized:
$( function() { ...my startup code... });

Button.OnClientClick question

I'm gonna post some more code to show exactly what I'm trying to do,
I'm adding the button using programming code and not markup but the OnClick won't work (giving the following error:
System.Web.UI.WebControls.Button.OnClick(System.EventArgs)' is inaccessible due to its protection level.
Button btnopslaan = new Button();
btnopslaan.Text = "Opslaan";
btnopslaan.ID = "btnOpslaan";
btnopslaan.CssClass = ".opslaan";
btnopslaan.Click += new EventHandler(btnopslaanClick);
btnopslaan_arr[btn_count] = btnopslaan;
add_button(btnopslaan);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("success");
}
I just can't find out why this isn't working.
Anyone who can help me out?
You need to use OnClick for server side clicks rather than OnClientClick
Either you can use it inline >
<asp:Button id="btnopslaan" runat="server' OnClick="btnopslaanClick" />
Or in Code behind >
btnopslaan.Click+=new EventHandler(btnopslaanClick);
or you make it a postback call to the server. in your
aspx write:
<asp:Button runat="server" ID="buttonOpslaan" Text="opslaan" ></asp:Button>
codebehind write this:
protected void Page_Init(object sender, EventArgs e)
{
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
}
// mind: this method can be private
void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it with the AutoEventWireUp (recommended) like:
<asp:Button runat="server"
ID="buttonOpslaan"
OnClick="buttonOpslaan_Click"
Text="opslaan" ></asp:Button>
// mind: this method cannot be private, but has to be protected at least.
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or do it completely from code behind:
// note: buttonOpslaan must have an (autoassigned) ID.
protected void Page_Init(object sender, EventArgs e)
{
Button buttonOpslaan = new Button();
buttonOpslaan.Text = "opslaan!";
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
form1.Controls.Add(buttonOpslaan);
}
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it clientside with javascript in your ASPX (it will not reach the server)
<script type="text/javascript">
function buttonOpslaan_Click(){
alert("test");
return false;
}
</script>
<asp:Button runat="server"
ID="buttonOpslaan"
OnClientClick="buttonOpslaan_Click()"
Text="opslaan" ></asp:Button>
Update: (by comments)
if you add the control via an eventhandler (like the onchange event of a dropdownlist), the control is 'lost' on next postback, or even as soon as the Page is send to the client (due to the stateless (there is no mechanism to maintain the state of application) behaviour and lifecycle of .Net).
So simply adding a control once is never going to work.
That means you have to rebuild the control every time a postback occurs. My preferred way to do this is store a list/document somewhere that descrbes what controls must be created each time. Possible locations are, from worse to good (IMHO):
Session
Viewstate
Cache
XML/IO
Database
After all, you are posting "data" to the server (that represents a control) and you want to save that for further use.
If the controls to be created aren't that complex you could implement a Factory Pattern like a WebControlFactory that stores only a few properties in a List or Dictionary, which is read every time to recreate the controls again (and again, and again, and again)
btnopslaanClick should be client side, in the .aspx itself have:
<script type="text/javascript">
function btnopslaanClick() {
alert("success");
}
</script>
btnopslaan.Click+=new EventHandler(btnopslaanClick);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("succes");
}

Categories