ASP.NET Web Application Message Box - c#

In an asp.net windows forms application, in the C# code behind you can use:
MessageBox.Show("Here is my message");
Is there any equivalent in a asp.net web application?
Can I call something from the C# code behind that will display a message box to the user?
Example usage of this: I have a button that loads a file in the code behind. When the file is loaded or if there is an error I would like to popup a message to the user stating the result.
Any ideas on this?

You want to use an Alert. Unfortunately it's not as nice as with windows forms.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);
Similar to this question here: http://forums.asp.net/t/1461308.aspx/1

Or create a method like this in your solution:
public static class MessageBox {
public static void Show(this Page Page, String Message) {
Page.ClientScript.RegisterStartupScript(
Page.GetType(),
"MessageBox",
"<script language='javascript'>alert('" + Message + "');</script>"
);
}
}
Then you can use it like:
MessageBox.Show("Here is my message");

Here is a link from Microsoft that I think is the best way to present a MessageBox in ASP.NET
Also it presents choices like Yes and No.
Instructions on how to get the class from the link working on your project:
If you don't have an App_Code folder on your Project, create it.
Right click the App_Code folder and create a Class. Name it MessageBox.cs
Copy the text from the MessageBox.cs file (from the attached code) and paste it on your MessageBox.cs file.
Do the same as steps 2 & 3 for the MessageBoxCore.cs file.
Important: Right click each file MessageBox.cs and MessageBoxCore.cs and make sure the 'Build Action' is set to Compile
Add this code to your aspx page where you want to display the message box:
<asp:Literal ID="PopupBox" runat="server"></asp:Literal>
Add this code on you cs page where you want to decision to be made:
string title = "My box title goes here";
string text = "Do you want to Update this record?";
MessageBox messageBox = new MessageBox(text, title, MessageBox.MessageBoxIcons.Question, MessageBox.MessageBoxButtons.YesOrNo, MessageBox.MessageBoxStyle.StyleA);
messageBox.SuccessEvent.Add("YesModClick");
PopupBox.Text = messageBox.Show(this);
Add this method to your cs page. This is what will be executed when the user clicks Yes. You don't need to make another one for the NoClick method.
[WebMethod]
public static string YesModClick(object sender, EventArgs e)
{
string strToRtn = "";
// The code that you want to execute when the user clicked yes goes here
return strToRtn;
}
Add a WebUserControl1.ascx file to your root path and add this code to the file:
<link href="~/Styles/MessageBox.css" rel="stylesheet" type="text/css" />
<div id="result"></div>
<asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="True">
</asp:ScriptManager> //<-- Make sure you only have one ScriptManager on your aspx page. Remove the one on your aspx page if you already have one.
Add this line on top of your aspx page:
<%# Register src="~/MessageBoxUserControl.ascx" tagname="MessageBoxUserControl" tagprefix="uc1" %>
Add this line inside your aspx page (Inside your asp:Content tag if you have one)
<uc1:MessageBoxUserControl ID="MessageBoxUserControl1" runat="server" />
Save the image files 1.jpg, 2.jpg, 3.jpg, 4.jpg from the Microsoft project above into your ~/Images/ path.

Not Really. Server-side code is happening on the server. You can use JavaScript to display something to the user on the client side, but it obviously will only execute on the client side. This is the nature of a client server web technology.
You're basically disconnected from the server when you get your response.

Why should not use jquery popup for this purpose.I use bpopup for this purpose.See more about this.http://dinbror.dk/bpopup/

There are a few solutions; if you are comfortable with CSS, here's a very flexible solution:
Create an appropriately styled Panel that resembles a "Message Box", put a Label in it and set its Visible property to false. Then whenever the user needs to see a message after a postback (e.g. pushing a button), from codebehind set the Labels Text property to the desired error message and set the Panel's Visible property to true.

'ASP.net MessageBox
'Add a scriptmanager to the ASP.Net Page
<asp:scriptmanager id="ScriptManager1" runat="server" />
try:
{
string sMsg = "My Message";
ScriptManager.RegisterStartupScript(Page, Page.GetType, Guid.NewGuid().ToString(), "alert('" + sMsg + "')", true);
}

As others already pointed out, a message box will be clientside Javascript. So the problem then is how to force a clientside JS message box from the server side. A simple solution is to include this in the HTML:
<script>
var data = '<%= JsData %>';
alert(data);
</script>
and to fill this data from the server side code-behind:
public partial class PageName : Page
{
protected string JsData = "your message";
Note that the string value should be a Javascript string, i.e. be a one-liner, but it may contain escaped newlines as \n.
Now you can use all your Javascript or JQuery skills and tricks to do whatever you want with that message text on the clientside, such as display a simple alert(), as shown in the above code sample, or sophisticated message box or message banner.
(Note that popups are sometimes frowned upon and blocked)
Note also that, due to the HTTP protocol, the message can only be shown in response to an HTTP request that the user sends to the server. Unlike WinForm apps, the web server cannot push a message to the client whenever it sees fit.
If you want to show the message only once, and not after the user refreshes the page with F5, you could set and read a cookie with javascript code. In any case, the nice point with this method is that it is an easy way to get data from the server to the javascript on the client, and that you can use all javascript features to accomplish anything you like.

Here's a method that I just wrote today, so that I can pass as many message boxes to the page as I want to:
/// <summary>
/// Shows a basic MessageBox on the passed in page
/// </summary>
/// <param name="page">The Page object to show the message on</param>
/// <param name="message">The message to show</param>
/// <returns></returns>
public static ShowMessageBox(Page page, string message)
{
Type cstype = page.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = page.ClientScript;
// Find the first unregistered script number
int ScriptNumber = 0;
bool ScriptRegistered = false;
do
{
ScriptNumber++;
ScriptRegistered = cs.IsStartupScriptRegistered(cstype, "PopupScript" + ScriptNumber);
} while (ScriptRegistered == true);
//Execute the new script number that we found
cs.RegisterStartupScript(cstype, "PopupScript" + ScriptNumber, "alert('" + message + "');", true);
}

if you will include
System.Windows.forms
as namespace then it will conflict .
Use
btn_click()
{
System.Windows.Forms.MessageBox.Show("Hello");
}

You need to reference the namespace
using System.Windows.Form;
and then add in the code
protected void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show(" Hi....");
}

Right click the solution explorer and choose the add reference.one dialog box will be appear. On that select (.net)-> System.windows.form. Imports System.Windows.Forms (vb) and using System.windows.forms(C#) copy this in your coding and then write messagebox.show("").

Just add the namespace:
System.Windows.forms
to your web application reference or what ever, and you have the access to your:
MessageBox.Show("Here is my message");
I tried it and it worked.
Good luck.

Related

c# asp.net response.write shrinks text boxes

I have a Web Form project I am developing C# ASP.Net 4.5. I have a class that calls a response.write to display a message for user input validation purposes. The call to response.write is made inside the class in a method from creating a new instance of the class, thus the class method, by pressing a button on the form. But using the response.write causes the textboxes on my page to shrink considerably. Then when I press a different button the textboxes go back to normal. It only happens when I use response.write. Any help would be appreciated. Code call in class method:
HttpContext.Current.Response.Write("File not found");
By using that you're simply dumping text to the top of the page, typically outside of the <html> tags. This can have a knock-on effect to the rest of the pages style; i see the same when i am spitting out test responses.
Instead, put yourself a label control on your page and populate that instead. you can put it exactly where you want and simply call:
So put this: <asp:Label runat="Server" id="myLabel" /> where you want the message to appear.
Then in your code-behind, write this. It will populate the label with the given text.
myLabel.Text = "File not found";
The Label control will be rendered as a <span></span> - so styling it is nice and easy.
If you fancied using a <div> then use the Panel control.
If you're not fussed about any sort of style, go for a Literal control, which renders no html elements.
When you use the HttpContext.Current.Response.Write on code behind is direct send to the page your text, at any random point of page render.
Maybe on top, maybe on bottom, on some point that you can not control if you use the code behind to call it.
Change the way you show your message, at a minimum you can use a literal control to render there your output and show it.
You may want to use a control to display your error. For example:
In the aspx/ascx
<asp:Label id="ErrorMessage" runat="server" />
in the page/control code behind
//call TheClass
TheClass c = new TheClass();
string error = c.TheMethod();
if (!string.IsNullOrEmpty(error))
{
ErrorMessage.Text = error;
}
in TheClass
public class TheClass
{
public string TheMethod()
{
string result = "";
...
//When file is not found
result = "File not found";
...
return result;
}
}

How do I fire a aspx script when a dynamically added button is clicked?

Here is the context:
I am building a .aspx page that allows the user to administrate some xml documents we have on our server. The page content is loaded using AJAX, so buttons and forms are dynamically added to the document.
If I had static buttons that I was creating within the .aspx page before it loads on the client's machine, I could attach an event to it very easily. However, I'm dynamically adding and removing buttons and forms on the fly, using jQuery.
Here is a simplified example:
In the following jsFiddle, I'm pretending that the html document contains the following script:
<script language="C#" type="text/C#" runat="server">
void SaveAllChanges(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
clickedButton.Text = "foobar";
}
</script>
And that I have a javascript file that contains the following:
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
Obviously the buttons I am creating can not run the function SaveAllChanges with the way it is now. I added the onclick attribute to show what I needed to happen, in a pseudo-code kind of style.
How can I make it so that dynamically added buttons can run the C# method I have defined within the script tag at the top of the document?
Here is the jsfiddle: http://jsfiddle.net/2XwRJ/
Thanks.
You can give all buttons that must save changes a common class (e.g. class="ajaxButton") and have one jQuery method that responds to click events on elements matching that class (use live so that updates to the DOM are reflected).
$("button.ajaxButton").live("click", function(){
// Perform your Ajax callback to run server-side code
});
What you need to do is use something like ..
$(document).ready(function() {
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button id="#dynamicCommentButton" onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
$(document).on('click', '#dynamicCommentButton', function() {
alert($(this).attr('id'));
});
});
You are not going to be able to add the buttons like you have it there as this code here is just adding it as an HTML DOM element and the onclick attribute will be the on the client element. As a result clicking the button will try fire a SaveAllChanges javascript function
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
What would be best would be to create that SaveAllChanges function in javascript and then you can handle it from there. Two of the ways I see you being able to do this are:
Have a http endpoint setup (script service, web api or just posting to a page) that you call using Ajax from your javascript. You can then pass through any needed arguments.
You could have a hidden element and hidden button on the page so that when the javascript is called it populates any arguments you need and then clicks the hidden button and posts the page back.
Personally I would choose the first approach from a user experience stand point as the page will not be posting back each time. I have used something similar to the second approach and it works fine but just feels very clunky.

Ajax AsyncFileUpload fires server code but does not update client web page

I have an asyncfileupload control inside an update panel. The file succesfully upload and fires the correct server side code. The code on the server is exected as expected however, one line in the server code changes the text on a label. I step through the code in debug mode and the line is executed but no change is made to the page.
Here's some of the code:
<asp:UpdatePanel runat="server" ID="updater" >
<ContentTemplate>
<asp:AsyncFileUpload ID="fileUpload" runat="server" OnUploadedComplete="FileUploadComplete" />
<asp:Label ID="AsyncText" runat="server" Text="File Type not checked" />
</ContentTemplate>
</asp:UpdatePanel>
public void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
System.Threading.Thread.Sleep(500);
if(fileUpload.HasFile) { AsyncText.Text = "file of correct format: "; }
}
Can anyone help me with solving this problem or offering annother solution??
Thanks
I think you are going to have to move toward a different solution. From your label message, it looks like you are trying to check the file type, correct? Basically, the AsyncUplaod control, although posting back to get the uploaded file to the browser, is not actually updating the page's viewstate, thus the label never gets updated. Boo! I was able to visualize this using this code in the page load event.
if (Page.IsPostBack)
{
if (Request.Files.Count > 0)
{
AsyncText.Text = "file of correct format";
ListItem item = new ListItem("item to add");
lb.Items.Add(item);
}
}
This was allowing me to set the label text but still nothing changed until I clicked on a random button that I added to the page. This button didnt even have an event in the code behind, but it was enough to cause a normal postback, and the label text and list item were successfully updated/added to the list. With that said, I would wait to update any labels until the user clicks upload by using a seperate upload button. (ie use the AsyFileUplaod to get it to the browser, but another button to save the file to the server). You can always do file evaluations in the button click event by referencing the posted files to the webpage as I did in the code above.
Some other examples I found online were using javascript to change the label text which works well also. Somthing like this:
string message = "";
if (e.StatusMessage == "Success")
{
message = "File upload successful;";
}
else
{
message = "File did not upload successfully;";
}
ClientScript.RegisterStartupScript(this.GetType(), "akey", "document.getElementByID('label').value =" + message, true);
Another example: here
I think in this case it's just the nature of the control and the only way to achieve what you want is though some creative thinking. If you have any other questions about anything I listed here feel free to ask.
Good luck!
Where is the label positioned, inside or outside the update panel? Seems like the partial page update may not be including the update to the label text. I would say move the label around as the simplest suggestion, but you could also try something like RegisterStartupScript which will change the lable text via javascript. This should still give you server side control over what text to display based on what happens during the upload.
If you could post some code that would be great.

Creating and showing dynamic error messages (Not working inside UpdatePanel)

My web forms inherits a class called MyPageMain, which inhertis System.Web.UI.Page and is located on the App_Code folder.
In this MyPageMain class I created this method, to record and output Exceptions (error messages):
public string Error(Exception pException, string pFriendlyMessage)
{
using (BusError erro = new BusError())
{
int? errorId = //HERE Routine to log the error;
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, "erroMain");
writer.RenderBeginTag(HtmlTextWriterTag.Div); //<div>
writer.RenderBeginTag(HtmlTextWriterTag.P); //<p>
writer.Write(pFriendlyMessage);
writer.RenderEndTag(); // </p>
writer.RenderBeginTag(HtmlTextWriterTag.Small);
writer.Write("Event tracker:");
writer.Write(errorId);
writer.RenderEndTag();
writer.RenderEndTag(); // </div>
Console.WriteLine(stringWriter.ToString());
}
}
}
Then, when there is some exception on the page, I call it, like this:
Protected void btnLoad_Click(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
//Loading some data here.
}
catch (Exception ex)
{
Error(ex, "Unexpected error trying to load data.");
}
}
This is bulding OK, but doesn't work... I think that one of the reasons may be the fact that the whole thing is inside an UpdatePanel. Any suggestions on how to make this work?
Is this Console.Writeline suitable for what i'm trying to do? Is this going to work on UpdatePanels?
Already Tried with Response.Write(...) and it does work. But not inside an UpdatePanel
When you use an UpdatePanel, you can only update content within the panel during an async postback triggered from that panel, so your error message will have to appear somewhere within the UpdatePanel. (That is, unless you set UpdateMode="Always" on one of your UpdatePanels, then its content is updated on every async and full postback. But that doesn't help you here unless you put your error message in its own UpdatePanel with UpdateMode="Always", which would require you to add said UpdatePanel to every page. I understand this is not what you want to do.)
The following example will work to add the error message at the top of the UpdatePanel.
You will need to add a Control errorParent parameter to your Error method, so it can add the error message as child control to that parent control.
In your catch block, just pass in whatever container control where you want the error message to appear. That control must be a container to accept child controls, so it has to be something that renders as a <div> or <span> tag, like an asp:Panel or asp:UpdatePanel.
In the example below, you could use errorParent.Controls.Add(errorControl) to show the error message at the bottom of the UpdatePanel, or use AddAt() with a different index. Just be sure that index will always work on every page.
Take a parent control and add a new Literal child control:
public string Error(Exception pException, string pFriendlyMessage, Control errorParent)
{
using (BusError erro = new BusError())
{
int? errorId = //HERE Routine to log the error;
Literal errorControl = new Literal();
errorControl.Text = String.Format("<div class=\"errorMain\"><p>{0}</p><small>Event Tracker: {1}</small></div>", pFriendlyMessage, errorId);
errorParent.Controls.AddAt(0, errorControl);
}
}
Pass in the parent control:
private void LoadData()
{
try
{
//Loading some data here.
}
catch (Exception ex)
{
Error(ex, "Unexpected error trying to load data.", MyUpdatePanel.ContentTemplateContainer);
}
}
Since your Error method returns string, you can return error message and display it.
Place Literal in your UpdatePanel (maybe in MasterPage, so you do not have to write it for all 40 or more pages). When exception is thrown, handle it with your Error method and set returned message to Literal.
Console.WriteLine is not usable in ASP.NET. Use Debug.WriteLine instead. It will write to Output window in VisualStudio.
Many of the answers are dancing around the issue. Console.WriteLine is a command used to output a line of text for a Console application (command-line). This is a Web app. So, you either use Response.Write to spit a string out to the Response stream or set the text of a Literal control that is already on the page and set it to be visible (default hidden).
Since I myself completely missed the UpdatePanel detail, here's an alternate solution to make up for it. My example uses a hidden div and some jQuery through the usage of the ScriptManager control to inject text into a div that is outside the UpdatePanel. Based on the conditions of the go_Click handler method of the button, it'll show or hide an error message using jQuery that gets injected into the Page server-side at the time of the UpdatePanel's update.
Note that it is critically important to use the ScriptManager's functions to register JavaScript rather than Page.ClientScript when using AJAX. Using the latter won't add the JS to the page.
Page markup
<div id="errorMessagePlaceHolder" class="error" style="display:none;">
</div>
<asp:UpdatePanel ID="myPanel" runat="server">
<ContentTemplate>
<asp:TextBox ID="myText" runat="server" />
<asp:Button ID="go" Text="GO" runat="server" OnClick="go_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Page code-behind
public partial class _Default : Page {
protected void go_Click(object sender, EventArgs e) {
try {
// Do something that can throw an exception
// Hide the error if we reach the end as we may have triggered
// it in a prior update and no longer want it to display.
HideError();
} catch (Exception) {
ShowError("myText is empty!");
}
}
#region Move to a base page or a helper class if it helps reduce duplication
private void HideError() {
ScriptManager.RegisterStartupScript(Page, GetType(), "HideErrorMessageScript", HideErrorMessageScript(), true);
}
private void ShowError(string errorMessage) {
ScriptManager.RegisterStartupScript(Page, GetType(), "ErrorMessageScript", ErrorMessageScript(errorMessage), true);
}
private static string HideErrorMessageScript() {
return #"
$(document).ready(function() {
$('#errorMessagePlaceHolder').hide();
});
";
}
private static string ErrorMessageScript(string errorMessage) {
return
string.Format(
#"
$(document).ready(function() {{
$('#errorMessagePlaceHolder').html('{0}');
$('#errorMessagePlaceHolder').show();
}});
",
errorMessage);
}
#endregion
}
I feel like nobody has actually answered the entire question yet, so let me try.
Is this Console.Writeline suitable for what i'm trying to do?
Probably not, unless you just want debug information to appear in the output window while debugging. Some people like to keep outputting info to the Console, even in a release build and so if you want to do that with your errors, it's a valid choice, but you should also be showing a friendly error message to the user and/or logging the error to some kind of persistence (eg. log file). All of the answers above are suggesting ways for you to show some notification of the error to the user.
Is this going to work on UpdatePanels?
There is NO reason why it shouldn't if your triggers and the like are set up properly (and we know they are because you said that you're able to hit the Console.WriteLine breakpoint). I wonder if your Console output is working fine but you're looking for it in the wrong place? In the typical configuration for a web application, it should appear in the Output window of the Visual Studio instance you're using to Debug.
As to a suggestion for what I think you're asking, which is "how do I get my error message to appear in the update panel if there's an error loading the content for that update panel?"...
I would suggest an approach similar to nekno's proposal above. You can either dynamically add a control whose text you can set to be the error string during update panel request processing or you can even have an initially hidden/collapsed control on the page, which is only set to be visible in the case of an error. I'd prefer the latter approach because it's more maintainable. You can completely control the look and feel of the error label from the markup/display views of your ASPX page.
Are you calling .update() on your UpdatePanel after your LoadData() method runs? I think the UpdatePanel won't automatically fire unless the postback originates from inside it.
Ex:
Protected void btnLoad_Click(object sender, EventArgs e)
{
LoadData();
MyUpdatePanel.Update();
}
Update: I was able to get Response.Write() to work in an UpdatePanel by registering a trigger like this <Triggers><asp:PostBackTrigger ControlID="btn1" /></Triggers> for the button that will create the error.
Are you trying to log errors or display them? If you are trying to display them, you should:
On your masterpage, create a spot where your errors will be displayed (maybe below your navigation bar or near the bottom:
<asp:ContentPlaceHolder id='cphError'></asp:ContentPlaceHolder>
Everytime you get an error, you can call your error function as is, but instead of writing out the text with Response.Write() or Console.WriteLine(), you can add a label in there:
Label lError = new Label();
lError.CssClass = '..';
lError.Text = '..';
cphError.Controls.Add(lError);
This will help you out with displaying the error, but AJAX will still be a problem. At this point, you have two options:
Since update panels update other update panels, you can wrap an update panel around cphError, this way your AJAX calls will still update that area
OR: You can can use ClientScript.RegisterStartupScript to create the error label. (This method is only preferable if you do not have a static error message spot)
Place a Panel on the master, extend it with the modalpopupextender in the AjaxToolKit. When the error is raised, write the contents of string writer to a label in the panel E.g. Label lbl = (Label)Master.FindControl()
lbl.text = StringWriter.ToString();
// Now access the modal popup
AjaxControlToolkit.ModalPopupExtender MPE = (AjaxControlToolkit.ModalPopupExtender)Master.findControl("");
// and show it
MPE.Show();
The Modal will need a hidden button to use as it's target control, but it will not require a user's input. I accomplish this on the page with the following code:
<asp:Button ID="btnDummyOK" runat="server" Style="display: none;" />
<asp:ModalPopupExtender ID="mpePnlErrors" runat="server" TargetControlID="btnDummyButton" PopupControlID="pnlErrirs" BackgroundCssClass="modalBackground" CancelControlID="btnCancel" OkControlID="btnOK" />
Good luck
I think Console.WriteLine don''t work on asp.net application and i think inside an update panel you can simple fire the throw New Exception( the friendly error message) and it will appear in an alert box.

How do I generate JavaScript during an AJAX callback (postback) and then execute it on the browser?

In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.

Categories

Resources