I have this code behind in my ASP.NET 4 Web Forms app:
Protected Sub BTNSave_Click(sender As Object, e As EventArgs) Handles BTNSave.Click
If saveOnDB() Then
showOkAlert()
Else
showErrorAlert()
End If
End Sub
I need to show a client alert when something done in the code behind has gone OK or an error has happened. Any idea?
I haved tied Response.Write("<script>alert('Successfully added');</script>") but this never works and even creates an error in the browser's console: "Uncaught Sys.WebForms.PageRequestManagerParserErrorException: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed."
Also I don't use OnClientClick because it triggers the javascript before the codebehind.
I do something similar. I've hacked some working code to simplify it as an example for your particular use:
private void RegisterJavascriptForUpdatePanelExample(UpdatePanel myUpdatePanel, string myMessage)
{
const string JAVASCRIPT_TEMPLATE = "javascript: jQuery(function($) {{ alert({0}); }});";
const string SCRIPT_KEY_TEMPLATE = "KeyForRegisterJavascriptForModalPopup_{0}";
string scriptkey, scriptstr;
scriptkey = string.Format(SCRIPT_KEY_TEMPLATE, myUpdatePanel.ClientID);
scriptstr = string.Format(JAVASCRIPT_TEMPLATE, myMessage);
ToolkitScriptManager.RegisterClientScriptBlock(myUpdatePanel, myUpdatePanel.GetType(), scriptkey, scriptstr, true);
}
In this example, a simple JavaScript alert() is called to display your message, like this:
RegisterJavascriptForUpdatePanelExample("A-OK!");
Of particular interest is the ToolkitScriptManager.RegisterClientScriptBlock function. There are several variations of this, depending if the JavaScript code should be embedded and executed within an UpdatePanel, or when the page loads, or other situations. It can be kind of confusing to decide which function is needed, but it's just what you need.
Related
I'm facing a strange anomaly in C# (ASP.NET Web Forms).
I have an ascx Web Page where I call a function creating a JSON from localStorage values.
function creerJsonDepuisLocalStorage() {
var modif = {}
// Filling modif with localStorage values ...
try {
return JSON.stringify(modifs);
} catch (e) {
console.log(e);
return "";
}
}
My codebehind is called on submit button click and recover the JSON to use it.
protected void btnEnregistrerFiche_OnClick(object sender, EventArgs e)
{
// tons of code ... doing various things like !!DataBase access!!
string argument = Request.Form["__EVENTARGUMENT"];
JavaScriptSerializer ser = new JavaScriptSerializer();
try
{
FicheModifiee edits = ser.Deserialize<FicheModifiee>(argument);
// edits treatments, commented for debug
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
// some other code like !!UI update!!
}
My problem is the following :
When my front end javascript function returns an empty string, the codebehind function works like a charm, doing database modifications and updating UI.
When my front end javascript function returns a real object, the codebehind function is correctly deserializing the JSON into the edits class and I don't have any bug or crashes BUT database access isn't made and UI is updating with previous data (not considering any changes made before submitting).
This sounds like dark magic as I'm not getting any crashes and my little piece of code isn't doing anything with the rest of the function ...
Thanks for your help.
I managed to fix my problem by using an asp:hiddentField (set at the end of my json creation script) and by reading it directly from C# code. Still not knowing what happend with Request.Form["__EVENTARGUMENT"];
I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/
I have a JavaScript function to passing a query string and when I get to the page that its being redirected to, but when I step through the code the id is not being passed.
the JavaScript is
function OpenRadWindow(sender, eventArgs) {
window.radopen("BankStatements_Update.aspx?id=" + eventArgs.getDataKeyValue("id"), "RadWindow1");
}
the code for the page to receive the query string is
string a = Request.QueryString["id"].ToString();
however if I use the selected change event then I can get the id using this in the code behind..
string a = (RadGrid2.SelectedItems[0] as GridDataItem).GetDataKeyValue("id").ToString();
this works fine, however I have been looking around for awhile now and can't find a way to open radwindow from the code behind.
I have tried using this script to call the javascript function to open the radwindow..
string script = "<script language='javascript' type='text/javascript'>Sys.Application.add_load(OpenRadWindow);</script>";
ClientScript.RegisterStartupScript(this.GetType(), "showWindow", script);
but it wouldn't fire.
So I am left to using the original script that I showed and I have no idea why I'm not getting the id.
window.radopen is framework method ? maybe is window.open?
ref http://www.w3schools.com/jsref/met_win_open.asp
or you can do that in your javascript function
function OpenRadWindow(sender, eventArgs) { console.log(eventArgs.getDataKeyValue("id"));}
And use browser console check your value
I have written a java script function in the skin file of the visual web Gui application which returns some value too. Now i am invoking the java script method from code behind.
public void XYZ( string message)
{
this.InvokeMethodWithId("testCall", message);
}
And javascript function is:--
function testCall(strGuid, txt) {
alert("hai Java script fired..");
return txt+ 'returned from JavaScript';
}
I want the value returned from JavaScript in the application. how can i achieve it. Is there in other method to invoke the methods of JavaScript?
I want something like this:--
public void Conect( string message)
{
string returnedvalue = this.InvokeMethodWithId("testCall", message);
}
Javascript is executed on the client so the return won't make it to the server.
A solution could be to use AJAX to send that value to the server. Stack Overflow is full of answers about AJAX.
Here's a good example.
#Amish Kumar,
As noted by other replies already, the client-side and server-side are not directly connected in web programming. The client is always the initiator of every request, and the server-side's "purpose" is to render a response, which will then be returned to the client for processing, in Visual WebGui this is usually some UI update processing. This basically means that your client script will not execute until the server-side has finished rendering the response, and the only way the client can get some message back to the server is to issue another request.
Think about how you need to use the MessageBox in Visual WebGui for instance. In order to receive the "response" from the MessageBox, you need to supply a callback handler in your server-side code, and then your server-side code will have completed creating the response, which is returned to the client. The client updates its UI and on some action to the MessageBox dialog, it sends a new request to the server, which interpretes the action and invokes your callback handler. In the callback handler you use Form.DialogResult to get the user action.
A very basic way to make this work in custom Visual WebGui code could be like the following code on a Form:
private void button1_Click(object sender, EventArgs e)
{
SendClientMessage("This is a test");
}
public void SendClientMessage(string strMessage)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("var objEvent = mobjApp.Events_CreateEvent('{0}', 'MessageEvent');");
sb.AppendLine("mobjApp.Events_SetEventAttribute(objEvent, 'Msg', '{1}');");
sb.AppendLine("mobjApp.Events_RaiseEvents();");
this.InvokeScript(string.Format(sb.ToString(), this.ID, strMessage));
}
protected override void FireEvent(Gizmox.WebGUI.Common.Interfaces.IEvent objEvent)
{
if (objEvent.Type == "MessageEvent")
MessageBox.Show(objEvent["Msg"]);
else
base.FireEvent(objEvent);
}
This code will not work unless you set your Visual WebGui applicaton for no Obscuring. In order for this code to work on an obscured application, you would need to add the JavaScript as an obscured JavaScript resource and it would work fine.
Palli
enter code here
I have two weird workflows that I'm able to fix.. I fixed them by accident by simply checking a style in ASP.NET code behind. I want to hear your theories as to why this occurs. I have a couple of my own, but I don't want to have any stereotypes from you reading this if I tell you my theory.
Setup:
So I have a button (event code below in various snippets) on an ASP.NET page that submits my form. There are two workflows that are causing an issue. In each workflow, a WCF service call is being made. The WCF service call sets the CSS visibility attribute to "visible" when it's invoked. And the response JavaScript function changes the visibility attribute back to "hidden".
In each of these two workflows, the button that submits my form is being pressed too quickly, and the WCF call never returns, and the WCF service errors out. The form is submitted, and everything is perfect (since the WCF call never changed anything in the form), it's just that I get the error. A nicer approach to fixing this is to disable the buttons when the WCF service call is happening, which is exactly why I'm making the AJAX spinner visible and hidden. But right now, I am fixing my issue by checking the style, to understand the black boxes of ASP.NET, the browser and JavaScript, and how they're interacting when ASP.NET checks a style.
When I run this code, I get the WCF error:
Private Sub SaveCancelDeleteButtonClick(ByVal sender As Object, ByVal e As SaveCancelDelete.DynamicButtonEventArgs) Handles SaveCancelDelete.CustomButtonClick
Dim valid As Boolean = ValidatePage()
Trace.Write(String.Format("Caught a button with event {0}", e.EventName))
... continued
When I run this code I DO NOT get the WCF error:
Private Sub SaveCancelDeleteButtonClick(ByVal sender As Object, ByVal e As SaveCancelDelete.DynamicButtonEventArgs) Handles SaveCancelDelete.CustomButtonClick
Dim x As String = ImageAjaxSpinner.Style("visibility")
Dim valid As Boolean = ValidatePage()
Trace.Write(String.Format("Caught a button with event {0}", e.EventName))
... continued
When I run this code I DO NOT get the WCF error:
Private Sub SaveCancelDeleteButtonClick(ByVal sender As Object, ByVal e As SaveCancelDelete.DynamicButtonEventArgs) Handles SaveCancelDelete.CustomButtonClick
If ImageAjaxSpinner.Style("visibility") = "visible" Then
Return
End If
Dim valid As Boolean = ValidatePage()
Trace.Write(String.Format("Caught a button with event {0}", e.EventName))
... continued
When I debug, this style is ALWAYS hidden in these two workflows (in the last 2 snippets obviously since I didn't have the style code in the first snippet). I have a couple theories, but I want to hear your theories as to why this is happening.
==========
Ideally, I should gray out the buttons during the WCF call, but this is merely a theoretical question.
FYI: The JavaScript is changing the visibility, not the ASP.NET code.
AJAX spinner:
<asp:Image ID="ImageAjaxSpinner" runat="server" ImageUrl="~/images/ajax-spinner.gif" style="position:absolute; top:0px; right:0px; visibility:hidden;" AlternateText="spinner" />
Snippet of JavaScript pseudo class WCF web service error function:
PreAccessioningLoadError: function(sender) {
jQuery(this.Elements.ImageAjaxSpinner).css("visibility", "hidden");
alert("error");
return false;
},
=============
8/24/2011 1:27pm update
When I run this code, I get the WCF error:
Private Sub SaveCancelDeleteButtonClick(ByVal sender As Object, ByVal e As SaveCancelDelete.DynamicButtonEventArgs) Handles SaveCancelDelete.CustomButtonClick
If ImageAjaxSpinner.Visible = True Then
Return
End If
Dim valid As Boolean = ValidatePage()
Trace.Write(String.Format("Caught a button with event {0}", e.EventName))
... continued
When I run this code, I get the WCF error:
Private Sub SaveCancelDeleteButtonClick(ByVal sender As Object, ByVal e As SaveCancelDelete.DynamicButtonEventArgs) Handles SaveCancelDelete.CustomButtonClick
' D-02568 - fixed
'If ImageAjaxSpinner.Style("visibility") = "visible" Then
' Return
'End If
' D-02568 - fixed
'Dim x As String = ImageAjaxSpinner.Style("visibility")
' D-02568 - not fixed; throws WCF error
'If ImageAjaxSpinner.Visible = True Then
' Return
'End If
' D-02568 - not fixed; throws WCF error
Dim x As Boolean = ImageAjaxSpinner.Visible
Dim valid As Boolean = ValidatePage()
Trace.Write(String.Format("Caught a button with event {0}", e.EventName))
... continued
This seems to be a mysterious thing happening in the black box of Mozilla Firefox, and works. It doesn't work in all browsers, so I didn't rely on this code at all! Unless a developer of Mozilla Firefox browser can answer my question, I won't change my answer here. I am disabling my buttons until the WCF service response comes back, so the end-user can't click the button until the data is there.