I am trying to show a javascript confirm box in the middle of some server side code and after getting user confirmation continue processing but confirm box does not show up. I even wrote some sample code but no success.
after some server processing I need to ask user a question and after user confirmation continue some other server code. it seems to be very simple. even alert box work. How can I solve it?
please note that I can not call javascript confirmbox straight from buttonclick I need to do some serverside code and if that was ok then I want to show a confirmbox for continuation.
here is the code
<asp:Button ID="btn_deletefromDB" runat="server" OnClick="btn_deletefromDB_Click" Text="Delete from Datatbase);" />
protected void btn_deletefromDB_Click(object sender, EventArgs e)
{
//Delete service from Database
// some server side processing code
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Do you want to delete it from runtime too? Click OK to proceed.');", true);
Label1.Text = "delete from runtime confirmed";
// continue and delete from runtime
//bla bla bla
}
Instead of triggering this in the code-behind, you should add it to the Button1 OnClientClick event like so:
<asp:Button ID="Button1" runat="server" OnClientClick="return confirm('Do you want to delete it? Click OK to proceed.');" OnClick="Button1_Click" />
Web applications do not work like this. You cannot ask for user input in the middle of page's server-side life-cycle. This question has to be asked client-side and user's response has to come to the server as part of the page's submitted data.
All ScriptManager.RegisterStartupScript does is contributes to the final html content that will be sent to the client when the page completes request processing. Keep in mind that by the time this html content arrives to client computer the user may have closed the browser and gone home.
Use AJAX to submit query to server and make the server code so that it does it’s processing in two parts. I don’t have any working examples of this but this is how it would work in general. For posting data to server you can use native AJAX objects in JS or any other library as others suggested and for processing data on the server side you can use generic handlers (ashx) instead of standard web pages.
Send request to the server.
Catch the first part of the processing via JS on the client page.
Show JS window
Submit the other part to server
You’ll have to send results of the first part of processing back to the client because server will not be able to connect second request with the first one by default.
Related
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.
When a user clicks a button on ASP.net page, I need to
Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control
Run a javascript function like in How to call javascript function from asp.net button click event
Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?
Try using the onClientClick property of the asp:button element.
Ex, on your .aspx file:
<script type="text/javascript">
function myFunction()
{
alert('hi');
}
</script>
...
<asp:button id="Button1"
usesubmitbehavior="true"
text="Open Web site"
onclientclick="myFunction()"
runat="server" onclick="Button1_Click" />
And in your code behind (.aspx.cs)
void Button1_Click (object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
More info at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.
So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.
You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)
The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.
protected void addSchoolButtonClick(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "MyKey1", "SchoolSearchPopUp();", true);
/*Some code*/
}
I am developing a website in asp.net.At a Hyperlink onclick event i want to call a javascript function"SchoolSearchPopUp()".this function is for creating a new popup window and it is working correctly.But my problem is ,a javascript function is calling or pop window opens only after executing the rest of the code in that function and that code need's some data that occurs as a result of popup.How can i create the popup before executing the rest of code in that function.
Change your postback trigger to something within the popup.
I don't think javascript can be called from code behind. C# is running from the server and java is all client side. There's a good explanation to a similar question here: http://forums.asp.net/t/1117189.aspx
If you need to execute a javascript function, you could try changing the hyperlink to a button and making use of the OnClientClick property. This executes script client side rather than calling a method on the server.
<asp:button id="Button1"
text="Click Here"
onclientclick="SchoolSearchPopUp()"
runat="server" />
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
You will need to write JavaScript on the page to handle the click of the button first and then call to the page method on the server.
Add an OnClientClick attribute to your button element and run your JavaScript method from there:
<asp:Button ID="TestButton" OnClientClick="SchoolSearchPopup()" Text="Click Me" OnClick="addSchoolButtonClick" runat="server"/>
<script type="text/javascript">
function SchoolSearchPopup()
{
alert("Popup");
}
</script>
If you want to execute some javascript before your postback you will need to register your hyperlink's click event to a js method, then submit your post to the server after performing whatever client side logic you are looking to run. (not the other way around, using RegisterStartupScript)
Example:
$("#myHyperLink").click(function() {
// do page logic, in your case show a modal window
$("#myModalDivContainer").show();
// submit your post to the server... replace targetClientID with ID of server control you're posting to
__doPostBack('targetClientID', '');
// NOTE: If you want to perform an AJAX request instead simply use some jQuery here instead. it's up to you how to handle the request from this point :)
});
Hope this helps!
I am working on a web application where I want to show a loading image (busy indicator) when my code create a xml file and download it I want to show the image in a div. I should use c# code only not update panel nor the jquery ajax technique. My code looks like:
protected void lb_DownloadXML_Click(object sender, EventArgs e)
{
this.imgLoading.Visible = true;
//all my code
this.imgLoading.Visible = false;
}
my image is
<img src="Images/loading_big.gif" width="50" height="40" runat="server" id="imgLoading"
visible="false" />
but its not working. Can anybody explain me how can I achieve this task.
thanks in advance.
To execute server side code from client machine, there is no other way other than UpdatePanel or Ajax. The client request should reach to the server to execute the request. And the way this happens is by PostBack or by Get request. PostBack will reload page, if you are not using UpdatePanel (I guess which you don't want) and second is GET, which again you don't want.
Update
According to #Lloyd
Yes it is possible, you can render contents to the page sequentially by setting the "Response.BufferOutput" property to false, writing directly to the Response.Output and Flushing the stream.
You should well understand that when you write any code on server side it is only reflected in the broswer after a successful postback. Over here if you write C# code to display an progress image then it would be displayed only after the postback is successful, that means after your XML file has been created and downloaded to the client end or after successful execution of lb_DownloadXML_Click().
So there is no way to achieve that using C# server side code, you have to rely on client side programming to achievev this.
Ok, I've got a lightbox with a small form (2 fields) in it, inside an UpdatePanel, and I want to close this lightbox (must be done via javascript) when the 'Save' button is pressed.
However, there is a need to have a server-side CustomValidator on the page, and I only want to close the lightbox if this returns as valid.
Does anyone know a way to trigger javascript (or jQuery) code from a server-side validator?
You can add a little snippet of code using the ScriptManager to execute after the response comes back to the UpdatePanel.
if (Page.IsValid){
ScriptManager.RegisterStartupScript(
customValidator1,
typeof(MyPageClass),
"closeBox",
"myLightBoxVariableOnThePage.close()",
true);
}
When that server side validator runs, it will send a whole new page to the browser. Anything that was shown in the browser before was destroyed, including any state kept in your javascript. If new page bears a strong resemblance to the old page, you should consider this a happy coincidence.
Therefore, the thing to do here is rather than executing a javascript function, have your CustomValidator make the correct changes to the page on success so that it's rendered to the browser correctly in the first place.