I have an ASP.NET page with two radio buttons. The buttons use an auto-postback to run server side logic. If you select the second button, the page posts back and correctly displays a message that the second button is selected. If the browser back button is now clicked, the state of button 2 stays checked while the message reverts to saying that button one is checked. This results in a situation that is obviously undesirable because the state of the radio buttons and message are now out of sync. I know this is a caching issue but I find it odd that the browser remembers the previous state of the label but not the previous state of the radio button.
What is the best way to handle this situation? It's undesirable in this situation to disable cache or the use of the back button.
The following code example exhibits this behavior:
[Form:]
<asp:RadioButton ID="rb1" runat="server" AutoPostBack="true" Text="Button1" OnCheckedChanged="rb_CheckedChanged"
GroupName="rbgroup" Checked="true" />
<br />
<asp:RadioButton ID="rb2" runat="server" AutoPostBack="true" Text="Button2" OnCheckedChanged="rb_CheckedChanged"
GroupName="rbgroup" />
<br />
<hr />
<asp:Label ID="lbl1" runat="server">Button 1</asp:Label>
[Code Behind:]
protected void rb_CheckedChanged(object sender, EventArgs e)
{
if (rb1.Checked == true)
lbl1.Text = "Button 1";
else
lbl1.Text = "Button 2";
}
WYour issue is very simple.
In your markup you can use the checked="false" or whatever asp.net equivalent....
On page load make sure that you use the if(!IsPostBack){ //set your group value. } to set the radio button's values from a data source or default values the first time the page loads. Every subsequent time will be excluded.
So here is an example:
if(!IsPostBack)
{
rb1.Checked = false;
rb2.Checked = false;
//or alternatively set the value from server data
}
In the case of hitting the back button the browser has already cached the page. Since neither of the check boxes are flagged as checked="false" in your markup or in your code, the browser will load the state of the page as it has it from cache.
If you want to change which radio button is selected, use #2 to set the value of the group since PageLoad event executes before pre-render and render.
Hmm - that is funny.
I can reproduce this. And what surprises me is that the source (view source of browser) shows the correct radio button checked (Button 1). The browser (I tested IE and FF) does not seem to render the source correctly (or not redraw the radio button; or is not showing the correct source).
Now the thing with the back button is a bit tricky. Mainly because there is not much you can do about it... HTTP is and will stay stateless and the back button on the client is "far away" from your web server. You cannot control it.
As an article about a similar topic you could read A Thorough Examination of "Disabling the Back Button".
What I am trying to say is that although I do not understand why the browser seems to be rendering something different from what the source tells it, I fear you are fighting a losing battle here.
The only thing I can currently think of would be to find some smart JavaScript that I am unable to provide that "does something" to make the browser redraw the screen after the user clicked the back button.
You can try this.
<script type="text/javascript">
$(document).ready(function () {
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload(true);
}
});
</script>
Related
While creating my login-form, I need a checkbox option, allowing user to show <asp:TextBox TextMode="Password"> input, or hide it back again, but it seems my <asp:CheckBox ID="chkShowPass"> does not process chkShowPass_CheckedChange event. I found an article on this topic (ASP.NET Checkbox.Checked is not working), where chkShowPass.AutoPostBack property set to true settles the problem.
When I have plain ASP.NET example to put <asp:CheckBox ID="chkShowPass"> in, I'm able to do that with no problem, but the key thing, I have now added <asp:UpdatePanel> element to prevent my website pages from auto-scrolling on button-clicks, and to make my good-basket UI (which lies in
Site.Master) update properly from those clicks.
What shall I do, to make my <asp:CheckBox ID="chkShowPass"> react to chkShowPass_CheckedChange event, but, still, keeping my Site.Master's content in <asp:UpdatePanel>? I will also appreciate, if you know any way to prevent page from upscrolling on click, without <asp:UpdatePanel>.
You can do it using jQuery. give id to Password Textbox and a checkbox
<script type='text/javascript'>
$(document).ready(function(){
$('#checkbox').click(function(){
if($(this).is(':checked'))
{
$('#password_id').attr('type', 'text');
}
else
{
$('#password_id').attr('type', 'password');
}
});
});
</script>
Remember to add jquery script in a page.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
I'm new to web programming with .NET.
I am developing a web page with webforms, and I want at a certain moment to programmatically show a modal window, for the user to accept or cancel, according to a question. Exactly what does the "confirm" function of JavaScript.
I tried to get it calling a JavaScript function:
Page.ClientScript.RegisterStartupScript (this.GetType (), "CallMyFunction", "MyFunction()", true);
But I need to do it without reloading the page, and I also need to control if the user has accepted or canceled and I do not know how to do it.
I've also tried getting it using the ModExPopupExtender control from DevExpress.
Can someone tell me a simple way to get what I want?
I can not understand how something so usual in web programming, and that PHP + javascript would not pose any problem can be so complicated.
All start in a one-button event on the code behind:
protected void btn1_Click(object sender, EventArgs e)
{
//I make a series of checks
//If certain conditions I want to show the confirm
//According to the user has chosen ok or cancel will perform a certain action
}
Onclientclick does not help me because before launching the "confirm" I have to do some checks on the server side.
Thank you very much.
You can use OnClientClick which is a property on most web controls.
I like to just bring up a simple confirm() dialog which executes the server code if the user clicks OK and does nothing if the user cancels the action:
<asp:Button runat="server" ID="btnSave" Click="btnSave_Click" Text="Save"
OnClientClick="return confirm('Are you sure you want to do this thing?');" />
You can do other things with it as well, but the key thing to remember is that anything you do in OnClientClick will happen before the page gets posted back to the server.
This is also perfectly valid:
<asp:Button runat="server" ID="btnSave"
OnClientClick="showModalConfirm('some message goes here');" ... />
<script>
function showModalConfirm(msg)
{
$(".modal .message").innerHtml(msg);
$(".modal").Show();
}
</script>
You can set the action that OnClientClick should perform in your codebehind in exactly the same way:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you want to do this thing?');";
}
You can use below code in c# to call javascript function. Below code will execute afterpostback() javascript function:
ClientScript.RegisterStartupScript(GetType(), Javascript, "javascript:afterpostback();", true);
And you can write code in javascript function to display any div or popup:
<script language="javascript" type="text/javascript">
function afterpostback() {
//Here you can write javascript to display div/modal
}
</script>
One way I've handled this previously was to have 2 buttons on the page. The first would be initially visible and labeled "Submit". The second would be initially hidden and labeled "Confirm". The "Submit" button would postback upon click and perform your server side checks/validation. If those checks failed, an appropriate error message would be displayed. If those checks passed, an appropriate "Please confirm your submission"-type message would be displayed, the "Submit" button would become hidden, and the second "Confirm" button would become visible. When that Confirm button was clicked, it would postback again and fully submit.
EDIT: I forgot to mention, there's a bit more to this that occurred to me after I initially posted. You'll have to protect the fields from being edited in the event the server-side verification is successful as you obviously don't want the user changing values and then clicking the Confirm button. That means disabling all the input controls - which could be a pain if you have a lot. You also have to give them a way to (intentionally) Edit in case the server side verification passes, you display the Confirmation, and they change their minds - so basically you'd need a third "Cancel/Edit"-type button that would put the form back in edit mode and show your initial Submit button.
I'm writing an application in C#. I would like to replace the value for the TEXT property after the user clicks (focuses) on a textbox. I would like to set the TEXT value to be blank instead of the words "ENTER NAME HERE" when they click to edit the textbox.
Front-end:
<asp:TextBox Text="ENTER NAME HERE" OnClick="MyTextboxID_OnClick" ID="MyTextboxID" runat="server"></asp:TextBox>
Code-behind:
protected void MyTextboxID_OnClick(object sender, EventArgs e)
{
MyTextboxID.Text = "";
}
I tried to find the answer to this question but the answers didn't quite match what I wanted to do.
I was hoping C# had something similar to Javascript's "OnClick" or "OnFocus" events. I added the OnClick event to the textbox for illustration purposes. This OnClick event doesn't work.
Thank you in advance for your help!
Remember that ASP.NET is primarly server-side. Actions that run in C# require a post-back to the server. The impact of this on a page can be mitigated somewhat by using AJAX, but this is why you don't see an "OnClick" event off the ASP control.
However, you can still use the Javascript "OnClick" event. Since Javascript runs on the client, and the interaction in this instance is entirely handled on the client, you should just use that.
If you are not comfortable using Javascript, you might want to look at TextBoxWatermark server side control.
It is available NuGet.
<asp:TextBox OnClick="MyTextboxID_OnClick"
ID="MyTextboxID" runat="server">
</asp:TextBox>
<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
TargetControlID="MyTextboxID"
WatermarkText="ENTER NAME HERE"
WatermarkCssClass="watermarked" />
You should simply use the following Placeholder="Enter text here."
Option One:
<asp:Textbox id="txtName" runat="server" placeholder="Enter name here." />
Option Two:
$("#<%= txtName.ClientId %>").setAttribute('placeholder', 'Enter name here.');
$("#<%= txtName.ClientId %>").attr('placeholder', 'Enter name here.');
For the Javascript implementation, you would simply place that in your View and wrap it in: <script type="text/javascript"></script>. Those are the ideal approaches to display text which clears on focus.
You could also utilize the Tooltip. Hopefully these examples assist you. Important note, I have no issues with compatibility in IE 8 with the Placeholder. Also these approaches won't force a Postback which can occur due to Server-Side. Which would force you to either do a Postback or implement a Update Panel / Ajax to hide the Postback.
Plugin: https://github.com/mathiasbynens/jquery-placeholder
Why don't you use the place holder attribute and not have to worry about replacing the text at all. This would show when the text box is empty but disappear on focus
Hi everyone I have a web form in which I am having a button on clicking which data back up is being taken, I used the following javascript :
<script language="javascript" type="text/javascript">
function showPleaseWait() {
document.getElementById('PleaseWait').style.display = 'block';
}
</script>
<asp:Button ID="btnTakebackup" runat="server" Text="Take Backup" Enabled="true"
onMouseDown="showPleaseWait()" CausesValidation="false" />
<div id="PleaseWait" style="display: none;">"Please Wait Backup in Progress.."</div>
Hi I am using a button to take a back up.
Now I want to show a message in btnTakebackup_Click() event, whether Back up was successful or not.
I used Response.Write("<script>alert('abcd');</script>"); in btnTakebackup_Click() event.
But the problem is that I want to show the page also, which is not showing instead white background is showing.
Thanks in advance...
To show a message box alert should be able to write out a new script to the response stream:
var script =
"<script type=\"javascript\">" +
"alert(\"Backup in progress, don't go!\");" +
"</script>"
Response.Write(script);
However much this is distasteful, I suppose it is sometimes "necessary".
You can add client side event handlers to ASP controls:
How to: Add Client Script Events to ASP.NET Web Server Controls
Cheers.
Do you really want it to be an alert? (You should know that they lock up the whole browser not just the tab your page is on), do your users really need to acknowledge the backup success by clicking ok or just be informed of it?...
I suggest you have a div on the page that says "Backup successful". The visibility of which can be set by a boolean property BackUpSuccess which you can set to true in the code behind you mention.
<div id="backUpSuccess" <%=BackUpSuccess ? "" : "style='display:none;'"%>>
Backup was successfull
</div>
...you can style the div as you like in your .css file to get attention.
If you really do want an alert you could run some JavaScript on page load to check the content of a hidden input that you set server side in similar fashion...but running javascript on page load is tricky...unless your using jQuery and then you will know it's very easy.
From your question, I understood that after clicking on the button, the data back up is happening, but the alert is not displaying as soon as you clicked the button.This is because you are calling the JavaScript in the button click event which will be fired only after all the code in the button click is executed.I suggest you to add a JavaScript function in the .aspx source page it self and call the JavaScript function as shown below:
<script ...>
function xyz()
{
alert('Please Wait');
}
</script>
and in button declaration
<asp:button id='btn_submit' runat="server" OnClientClick="return xyz();" />
I am creating a button dynamically in my code and attaching a click event to it. However I have to prevent people to click it while there is a process going on. So when it is clicked once, it should be disabled and when the process ends it should be enabled. How can I do that?
Thanks.
onclick="this.enabled=false" add this from your code behind to your control
btnAdd.Attributes.Add("onclick", "this.enabled=false;");
This link explains in detail http://encosia.com/2007/04/17/disable-a-button-control-during-postback/
If you are processing via ajax when the button is clicked-
1. Disable the button when processing starts
2. Enable the button after processing completes
If the button postbacks, the best way is to disable the button when it is clicked via javascript [I won't suggest jquery just for this particular task]. Since after postback the button will be enabled as it was earlier, you don't need to worry about enabling.
<asp:Button ID="btn" runat="server" OnClientClick="disable(this)"
Text="Click me!" OnClick="btn_Click" />
<script type="text/javascript">
function disable(control)
{
control.disabled="disabled";
//added alert to give the snapshot of what happens
//when the button is clicked
alert(100);
}
</script>
Hope this helps.
I would use an UpdatePanel arround the button. On click you can serverside disable the button. Use a trigger on the updatepanel that looks every x seconds if your extern process has returned a result. And I would advise you to source out long running processes into a windows service.