Connecting Tech Pros Worldwide Help | Site Map

ScriptManager in MasterPage

  #1  
Old June 30th, 2009, 10:38 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18
Hi all,

Can somebody help me figure out whats wrong with my program?

I created a site with the use of MasterPage..and with a plan of utilizing and abusing the capabilities of AJAX, I added the ScriptManager to create PageMethods.

Here's what I did:

1. I added the "ScriptManager" and the "JavaScript that calls the page method" in MasterPage...with Javascript inside the <body> tag and ScriptManager inside the <form> tag.

2. In the "Child Form", I created a HTML image component, and in the OnClick event it calls the JavaScript function which calls the PageMethod.


When I run the page it doesnt display any errors at all, but everytime I click the image component(which triggers the javascript func)..it displays "Error on page" at the bottom left side of the page and the desired output don't display.

You might be thinking that the error could be on the code(which probably true), but I tried the same code without using a MasterPage and it works without any error.

Any suggestion and advice will be very much appreciated. Thanks.
  #2  
Old June 30th, 2009, 02:06 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


It is very likely that this is a JavScript error.
You could use IE8 or FireFox's FireBug tool to debug the error.

-Frinny
  #3  
Old July 1st, 2009, 03:38 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


Hi Frinny!

Thanks for the reply.

Yeah I agree with you that it is very likely a JavaScript error. But why is it that, when I run the page in a single page(without using the MasterPage) and using the same JavaScript function, It executes smoothly? Isn't the error also something to do with 'ScriptManager' being placed in the MasterPage or something to that effect?

Btw, I placed the PageMethods inside a Base Class which inherits the System.Web.UI.Page and all pages inherits that Base Class. (I did this as it was mentioned in the other forum that PageMethods should be placed inside a BaseClass when using MasterPage)

Thanks.
  #4  
Old July 1st, 2009, 01:47 PM
Newbie
 
Join Date: Jul 2009
Posts: 1

re: ScriptManager in MasterPage


Hi krungkrung,

Can you pl tell that where the "JavaScript" function is written?

If the javascript function is written within UPDATEPANEL then there is a chance that script manager has discarded that function while rendering the page to browser. So I'd suggest to keep the function in separate file and register script file from the code behind.

Hope it helps,

Sudev Gandhi
  #5  
Old July 1st, 2009, 02:03 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


Sudev could be right...

You may need to register your JavaScript function with the ScriptManager...

We won't know until you share with us the error details that FireBug or IE8 tells you and give us more details on where/how you are defining your JS.

:)

-Frinny
  #6  
Old July 3rd, 2009, 03:01 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


hi Frinny and sudevg!

thanks for your generous reply.

sorry i forgot to post quickly, but i already figured out the problem.

the problem was just the control id being passed to the function. i found out that asp.net(correct me if am wrong) generates control id automatically, of every control within a page upon processing. eg, txtTextInput component would generate something like ctrl001_xxxxx_txtTextinput control id. So if I pass the "txtTextInput", which is the control's name, to the function, the javascript's document.getElementById('txtTextInput') will return nothing since "txtTextInput" is not considered or identified as a control id of any control found within the page.

so here's what i did..though i think its kinda ugly but its the simplest way i could think for the mean time(if you have any idea i would be more than grateful if you share it to me)...from the code behind I pass the control's client Id to java script function...like, "txtTextinput.ClientID"...and that's it. as simple as that and my whole day was even brighter when I made it run after a couple of hours thinking what should be the problem of the program when I know I coded it correctly....cheers!
  #7  
Old July 3rd, 2009, 02:30 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


The "control id" is accessible in your .NET code using the ClientID property of ASP.NET controls.

There are a few things that I can add to this.

First of all, if your element is calling a JavaScript method that does something to that element, you can access that element by referring to "this" in JavaScript.

For example, the following TextBox calls the JavaScript method "toUpper()" which changes the text entered into upper case. Note how I'm passing "this" as the parameter..."this" refers to the TextBox element (for simplicity sake I'm using pure HTML instead of asp for this example):
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <body>
  3.   <script type="text/javascript>
  4.     function toUpper(element){
  5.        element.value=element.value.toUpperCase();    
  6.     }
  7.   </script>
  8.   Enter some text: <input type="text" id="myTextBox" onkeyup="toUpper(this);" />
  9. </body>
  10. </html>
You can do the same thing with ASP elements....just pass the JavaScript function "this" and you'll have a reference to the element in your JavaScript.

If the JavaScript method does not modify the element that is calling it then you'll have to change things around a bit. Sometimes, if you don't want to pass the ClientID of the asp.net control into the method, you can dynamically print the ClientID directly into the JavaScript by calling the Response.Write() method using ASP.

In your ASP page you would have something like this:
Expand|Select|Wrap|Line Numbers
  1.   Enter some text: <asp:TextBox ID="myTextBox" runat="server" />
  2.  
  3.   <script type="text/javascript>
  4.     function toUpper(){
  5.       var element = $get('<%= myTextBox.ClientID %>');
  6.  
  7.       //The $get method is a method made available to us in the Ajax.NET
  8.       //framework. The Ajax.NET Framework is included with the page when
  9.       //you add a ScriptManager to the page. Since you have a ScriptManager
  10.      //on the page, you have access to this method. It is a short hand for
  11.      //javascript: document.getElementById() method. The following
  12.      //would accomplish the same thing:
  13.       //var element = document.getElementById('<%= myTextBox.ClientID %>');
  14.  
  15.        element.value=element.value.toUpperCase();    
  16.     }
  17.   </script>
Where in your .NET code you set the "onkeyup" for the myTextBox element.

Please note that <%= %> is class asp short hand for calling the Response.Write method. This will write the ClientID directly into the page so that you don't have to pass anything to the method.

This is only possible if your ASP element is on the same page as the JavaScript that it uses. If it's not on the same page then it's easier to just pass the element to the function.


-Frinny
  #8  
Old July 6th, 2009, 03:46 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


Hi Frinny! Thanks for that very informative post. I really appreciate it. Im kinda..'wow!'..and realized that I still have a lot of things to learn in asp.net....waaayyy to go krungkrung..(",)


thanks..thanks. really.
  #9  
Old July 6th, 2009, 05:37 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


Hi Frinny!

I just have a follow-up question...is it possible to pass a 'Page' as parameter from .Net procedure to a JavaScript function and return that passed 'Page' parameter to a VB.Net function...like:


Expand|Select|Wrap|Line Numbers
  1. Sub FromNet()
  2. Dim strTest As String = "<script language=javascript id='myClientScript'>ToJavaScript(" & MyPage & ");</script>"
  3.         Page.ClientScript.RegisterStartupScript(Me.GetType(), "testing", strTest )
  4. End Sub
  5.  
and the JavaScript would be:
Expand|Select|Wrap|Line Numbers
  1. function ToJavaScript(objPage)
  2. {
  3.     PageMethods.ReturnToNet(objPage);
  4. }
  5.  

Expand|Select|Wrap|Line Numbers
  1. Public Shared Sub ReturnToNet(ByVal myPage As Page)
  2.  
  3. call Kachurvahan(myPage )
  4.  
  5. End Sub
  6.  
  #10  
Old July 6th, 2009, 02:08 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


No this isn't possible.
The Page Object is a .NET Object....it doesn't exist in the browser.

What are you trying to do?
  #11  
Old July 7th, 2009, 05:21 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


Hi Frinny!

Thanks for asking.

Well, I dont know how am I supposed to tell and explain to you what I really want to do with my program....I just feel its kinda 'awkward' or embarrassing posting or sharing my 'noob' way of coding :) ...but I believe sometimes people need to be criticized to learn from others opinion...so I'll just try my best to explain it to you.

Here's what I want to do:

(Presentation:)
1. A page that has a maximum of 8 thumbnail images loaded in it.
2. An image container(bigger than the thumbnail images) for displaying of selected thumbnail image
3. A left and right navigations(so I can navigate images more than the maximum, eg. 9 - 30).
4. A delete button(deletes a selected image)

(Events:)
1. Upon loading of the page the default selected image would be the first thumbnail
2. Clicking thumbnail pic will display the image to image container..WITHOUT POSTING BACK.
3. Clicking the LR navigation buttons will navigate through other pics not currently displayed..WITHOUT POSTING BACK
4. Hitting delete button will delete the pic from the directory and database and refreshes the page(calling the function called in Page_Load)..WITHOUT POSTING BACK.


Here's what I did:

1. Created a function(LoadAllPhotos) that saved the images in an array using ClientScript.RegisterArrayDeclaration. So basically, images are preloaded.

2. Placed LoadAllPhotos in 'Page_Load' event

3. Upon calling the LoadAllPhotos(or inside my LoadAllPhotos)..I call the LoadPicture() and NavigatePicsRight() JavaScript functions using ClientScript.RegisterStartupScript

***LoadPicture() -- is a function called when thumbnail is clicked
***NavigatePicsRight() -- is a function called when the R nav btn is clicked and displays other preloaded thumbnail images within a page.

4. Hitting delete btn should delete Image and calls back the LoadAllPhotos() function(to refresh array of preloaded images) without posting back. -->unfortunately I still unable to do this using PageMethods since I placed the function LoadPicture() inside the current page which supposed to be in a PageBase.


Here's my code:


Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  4.  
  5.         If Page.IsPostBack = False Then
  6.             Call LoadAllPhotos(Request.QueryString("traceid"))
  7.         End If
  8.     End Sub
  9.  
  10. Protected Sub LoadAllPhotos(ByVal intUserTraceId As Integer)
  11.         Dim _clsColPicture As New List(Of Picture)
  12.         Dim _clsPictureBL As New PictureBL
  13.         Dim _clsDBTransaction As New DBTransaction
  14.         Dim _shrtPicCount As Short
  15.         Dim _strHTM As String = ""
  16.         Dim _strImgBorder = ""
  17.  
  18.         Dim strFilePath As String = "images/" & Left("0000000000", 10 - Len(intUserTraceId.ToString)) & intUserTraceId & "/Images/"
  19.         Dim strFileName As String = ""
  20.  
  21.         Try
  22.             _clsDBTransaction.BeginTransaction()
  23.             _clsPictureBL.RetrievePics(_clsColPicture, intUserTraceId)
  24.             For _shrtPicCount = 0 To _clsColPicture.Count - 1
  25.                 strFileName = strFilePath & "t_" & _clsColPicture(_shrtPicCount).FileName.ToString
  26.  
  27.                 Me.ClientScript.RegisterArrayDeclaration("arrPhotos", "'" & strFileName.Trim.ToString & "'")
  28.                 Me.ClientScript.RegisterArrayDeclaration("arrPicOwner", _clsColPicture(_shrtPicCount).OwnerId)
  29.                 Me.ClientScript.RegisterArrayDeclaration("arrPicIndex", _clsColPicture(_shrtPicCount).Id)
  30.  
  31.  
  32.                 If _shrtPicCount <= 0 Then
  33.                     'load first image if any
  34.                     Dim strFirtsImg As String = "<script language=javascript id='myClientScript'>LoadPicture('" & strFileName.ToString & "', " & _clsColPicture(_shrtPicCount).OwnerId & ", " & _clsColPicture(_shrtPicCount).Id & ", " & Request.Cookies("TraceIdCookie").Value & ");</script>"
  35.                     Page.ClientScript.RegisterStartupScript(Me.GetType(), "callLoadFirstPic", strFirtsImg)
  36.                 End If
  37.             Next
  38.  
  39.             'call javascript function NavigatePicsRight to load first group of pics
  40.             Dim strScript As String = "<script language=javascript id='myClientScript'>NavigatePicsRight();</script>"
  41.             Page.ClientScript.RegisterStartupScript(Me.GetType(), "callNavigatePicsRight", strScript)
  42.  
  43.             _clsDBTransaction.CommitTransaction()
  44.         Catch ex As Exception
  45.             _clsDBTransaction.RollbackTransaction()
  46.         Finally
  47.             _clsDBTransaction.EndTransaction()
  48.         End Try
  49.     End Sub
  50.  
  51.  
Here's my JavaScript function
Expand|Select|Wrap|Line Numbers
  1. //function for navigation of loaded pics
  2. function NavigatePicsRight()
  3. {
  4.     var strHtml = "";
  5.     var index; 
  6.  
  7.     ClearWarningText();
  8.  
  9.     if(i>arrPhotos.length-1) {
  10.        return;
  11.     }
  12.  
  13.     var strCookie = "";
  14.     strCookie = getCookie("TraceIdCookie");
  15.  
  16.     ii++;
  17.     iii = 0;
  18.     strHtml = "<table><tr>";
  19.     for(index=0;index < 8;index++)
  20.     {                
  21.         if(i<=arrPhotos.length-1) {                 
  22.             strHtml = strHtml + '<td><img src="'+arrPhotos[i]+'" Height="40px" Width="59px" onclick="javascript:LoadPicture(''+arrPhotos[i]+'', '+arrPicOwner[i]+', '+arrPicIndex[i]+', '+strCookie+');" onmouseover="this.style.cursor='hand';"/></td>';   
  23.             i++;
  24.             iii++;
  25.         }                          
  26.     }            
  27.     strHtml = strHtml + "</tr></table>"
  28.     document.getElementById("div_photoframe").innerHTML = strHtml;
  29.  
  30. function LoadPicture(strPicture, intPicOwner, intPicIndex, intCurrentUserId)
  31. {
  32.    var strNewString = "";
  33.    var strToFind = "";   
  34.    var expires = "";
  35.  
  36.    ClearWarningText();
  37.  
  38.    strToFind = strPicture.substring(strPicture.lastIndexOf("t_"));
  39.    strNewString = strPicture.substring(strPicture.lastIndexOf("t_") + 2);
  40.  
  41.    document.cookie = "PictureIndexCookie="+intPicIndex+"; "+expires+"; path=/";   
  42.    document.cookie = "PictureFileNameCookie="+strNewString+"; "+expires+"; path=/";   
  43.  
  44.    document.getElementById("picholder").innerHTML = '<img src="'+strPicture.replace(strToFind, strNewString)+'"  />';
  45.  
  46.  
  47. }  
  48.  



Im just thinking if I could place my LoadAllPhotos() procedure inside a base class instead of placing it within the current page


Sorry for the lengthy post but I hope I stated my point clearly. Thanks a lot.
  #12  
Old July 7th, 2009, 07:05 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


ERRATUM:

4. Hitting delete btn should delete Image and calls back the LoadAllPhotos() function(to refresh array of preloaded images) without posting back. -->unfortunately I still unable to do this using PageMethods since I placed the function LoadAllPhotos() inside the current page which supposed to be in a PageBase.
  #13  
Old July 7th, 2009, 02:47 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


Quote:
Originally Posted by krungkrung View Post
ERRATUM:

4. Hitting delete btn should delete Image and calls back the LoadAllPhotos() function(to refresh array of preloaded images) without posting back. -->unfortunately I still unable to do this using PageMethods since I placed the function LoadAllPhotos() inside the current page which supposed to be in a PageBase.
The .NET code you posted....is it in a content aspx page or is it in the MasterPage?

It doesn't really matter which it's in...unless you want the photos to be on every page in your site as opposed to one page.

Anyways, your Delete functionality is going to have to postback to the server if you want to delete the image off of the server.

It doesn't have to be a full page postback, you can do an asynchronous postback using AJAX.

Have you used AJAX before?
  #14  
Old July 8th, 2009, 02:23 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


Hi Frinny! Thanks again.

The .NET code I posted resides in the .aspx page and not in the master page. But I want to place it in a Base class. That's why I ask you if a 'Page' object can be used as parameter in .Net to JavaScript function transition, so I can replace the 'Me' with the passed 'Page' object parameter.

Nope. Never used AJAX before, but am applying it to my current project. So technically, Im a noob. :).

Well, I really don't have much idea on asynchronous postback using AJAX except that it uses Update Panel based from what I read. :D. Can you give me an idea how can I do that? You don't have to give me the code..just a step or a piece of hint on how I can apply that technique to my page...and the rest will be up to me to research. *winks*...thanks a lot Frinny.
  #15  
Old July 8th, 2009, 02:19 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


The UpdatePanel makes life easy for you. You place one on the page, and then you place any content that needs to be asynchronously updated within the the UpdatePanel. Now every time any element within the panel postsback to the server only that section of the page is updated upon return.

The thing you have to remember is that when you use an UpdatePanel the full ASP Page Cycle occurs on the server.

If you don't like this idea, and you just want to call a particular method on the server to do the delete...then consider using pure Ajax. Or you can consider using AJAX with WebServices (I have recently become very fond of this)...but it requires some knowledge of AJAX/JavaScript, JSON, and of course Web Services.

One other thing to consider, when registering Dynamic JavaScript in an Ajax enabled website, you should not use the ClientScriptManager to do so. Instead you should be registering your JavaScript using the ScriptManager (or ScriptManagerProxy).

I don't understand what you mean by "Base Class"?
I also don't understand what you mean by "JavaScript function transition"...
  #16  
Old July 9th, 2009, 03:18 AM
krungkrung's Avatar
Newbie
 
Join Date: Nov 2008
Location: Philippines
Posts: 18

re: ScriptManager in MasterPage


Hi Frinny! Thanks..thanks!

Sorry if I did not clearly explain my last post....:)


What I mean by placing my LoadAllPhotos() function to a Base Class is, instead of placing it to current .aspx page, I want to place it in another Class(which inherits System.Web.UI.Page) and my .aspx page will just inherit that class, so I can call LoadAllPhotos from my JavaScript using PageMethods of ASP.Net AJAX...but as what youve said, it is not possible to pass Page param to javascript, so I should not be wasting my time thinking of this, I guess..:).

Sorry If I used 'transition' in my last post. What I really meant was, calling JavaScript function from Code Behind and calling Code Behind function from JavaScript. Btw, this is the only way(method) I know to change my page's content without posting back..or should I say, without making the entire page refreshed like when you press the 'Refresh' btn of the browser. Thanks Frinny!
  #17  
Old July 9th, 2009, 02:27 PM
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North :)
Posts: 4,940
Provided Answers: 8

re: ScriptManager in MasterPage


Quote:
Originally Posted by krungkrung View Post
What I mean by placing my LoadAllPhotos() function to a Base Class is, instead of placing it to current .aspx page, I want to place it in another Class(which inherits System.Web.UI.Page) and my .aspx page will just inherit that class, so I can call LoadAllPhotos from my JavaScript using PageMethods of ASP.Net AJAX...but as what youve said, it is not possible to pass Page param to javascript, so I should not be wasting my time thinking of this, I guess..:).
No no it's not a waste of time...you have the right idea, you're just going about it the wrong way.

You should into putting the LoadAllPhotos into a Web Service. You can call the Web Service using the AJAX.NET Library.

When you talk about "Base Class" I automatically think "inheritance"....and I never did understand why people want to use inheritance in aspx pages.....they're just pages....they don't require something like: Animal(BaseObject)->Cat(Derived From Animal)->HouseCat(Derived from Cat).

The Web Services solution is actually a pretty good idea :) I've never done it with pictures before but I think it should work! Even if the web service simply returns a bunch of URL's to the pictures...you can dynamically create the HTML <img> tags to display the images which may be quicker than loading all of the images at the same time.

Quote:
Originally Posted by krungkrung View Post
What I really meant was, calling JavaScript function from Code Behind
You cannot call a JavaScript function from your C# code....because the JavaScript function executes in the web browser, whereas the C# code is executed on the server.

Using Ajax you can make a request to execute C# code, but the C# code can't call the JavaScript function. (Unless you want to use COMET...but I wouldn't recommend it until you have a clear understanding of JavaScript and AJAX)

Quote:
Originally Posted by krungkrung View Post
Btw, this is the only way(method) I know to change my page's content without posting back..or should I say, without making the entire page refreshed like when you press the 'Refresh' btn of the browser.
Not sure what you're talking about here....are you using an UpdatePanel?

-Frinny
Reply


Similar Threads
Thread Thread Starter Forum Replies Last Post
MasterPage and Ajax ScriptManager Ryan Liu answers 2 June 27th, 2008 09:09 PM
Calling javascript function in masterpage file using RegisterClientScript problem baburk answers 2 May 27th, 2008 12:22 PM
Ajax -- tabPanel -- To load a tabPanel when I click in the tabPanel fran_j_diaz@yahoo.fr answers 0 September 14th, 2007 11:25 AM
Webparts - Ajax.net = You must enable Web Parts by adding a ScriptManager to your page Ryan answers 0 May 16th, 2007 07:15 PM