Showing posts with label scriptmanager. Show all posts
Showing posts with label scriptmanager. Show all posts

Wednesday, March 28, 2012

calling javascript proxy functions from master.pages

I 've a master page with an scriptmanager with EnablePAgeMethods=true.

I want to call from that page a static methode from my page within client side with a call like PageMethods.DeleteFIle()-this beeing a javascript proxy class which supoused to be generated by the script manager.

The issue is that this call work well from a simple page but not from master page -on java script i 've got the PageMaster it's unknown.

Thank you

Hi,

Here is a sample made according to your requirement. Please try it:

[Master page]

<%@. Master Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title> </head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager> <input id="Button1" type="button" value="button" onclick="SayHello();"/> <input id="Text1" type="text" /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </div> <script type="text/javascript"> function SayHello() { PageMethods.Hello(onComplete); } function onComplete(result) { $get("Text1").value = result; } </script> </form></body></html>

[Content page]

<%@. Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %><script runat="server"> protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod] public static string Hello() { return "Hello world!"; }</script><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"></asp:Content>
Hope this helps.

I have nearly this exact scenario, but the result returned is always the complete markup for the page. Any ideas as to why this is?


Can you show me your code

I also have the same problem. The pagemethod callback shows full page markup instead of return value.

Here's the code

<%-- <Snippet1 Master page> --%>

<%@.MasterCodeFile="MasterPage.master.cs"Inherits="MasterPage"Language="C#" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headid="Head1"runat="server">

<title>UpdatePanel in Master Pages</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<pstyle="font-family: Playbill, Fantasy; background-color: olive; font-weight: bold;

font-size: xx-large;">

Master Page

</p>

<hr/>

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true">

</asp:ScriptManager>

<hr/>

<br/>

<asp:ContentPlaceHolderID="ContentPlaceHolder1"runat="server">

</asp:ContentPlaceHolder>

</div>

</form>

</body>

</html>

<%-- </Snippet1> --%>

<%-- <Snippent2 Child content page> --%>

<%@.PageCodeFile="Child.aspx.cs"Inherits="Child"Language="C#"MasterPageFile="MasterPage.master"

Title="UpdatePanel in Master Pages" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<asp:ContentID="Content1"runat="Server"ContentPlaceHolderID="ContentPlaceHolder1">

<pstyle="font-family: Playbill, Fantasy; background-color: aqua; font-weight: bold; font-size: xx-large;"> Content Page</p>

<hr/>

<scripttype="text/javascript">

function doload()

{

PageMethods.GetName(GetName_Complete);

}

function GetName_Complete()

{

if(arguments.length >0)

{

alert(arguments[0].toString());

//document.getElementById('<%=txt1.ClientID %>').value = arguments[0].toString();

}

}

</script>

<asp:TextBoxID="txt1"runat="server"></asp:TextBox>

<inputid="Button2"onclick="doload()"type="button"value="button"/><br/>

<br/>

<asp:UpdatePanelid="UpdatePanel2"runat="server">

<contenttemplate>

<asp:TextBoxid="txtChild"runat="server"></asp:TextBox>

</contenttemplate>

<triggers>

<asp:AsyncPostBackTriggerControlID="lnkChild"EventName="Click"></asp:AsyncPostBackTrigger>

</triggers>

</asp:UpdatePanel>

<asp:ButtonID="lnkChild"runat="server"OnClick="lnkChild_Click"Text="Ajax Update"/>

<hr/>

</asp:Content>

calling javascript functions

I am working on an ajax web page which has several controls including a ScriptManager control and the ajax Timer control. When the timer fires a tick I want the server side to perform some calculations and then call a client script function with the results. The client script will then do something with the results.

Also, I want to call another javascript function when I click a button.

I'm a bit rusty with javascript, so I'd like to see examples on how to make this work.

What and where exactly you want to do?

When the timer fires, I want the server to generate (calculate) a pair of integers (or possibly an array of pairs) and call a javascript function on the client side passing those numbers. The client will then "plot" points on a graphics window using some built-in drawing java functions I have. The timer will probably fire several times a second. The client does not need to make any calls to the server.

When a button is clicked, I want the server to call another javascript function (passing no arguments) which will erase the graphics window. The timer continues firing.

I have other buttons, to start and stop the timer, sliders to change the timer rate and other parameters, checkboxes and radio buttons which also affect the calculations, etc. All I need help with is making the client calls and passing the data. Is the ScriptManager useful in that respect? By the way, I'm kind of "new" in java.

I've seen scenarios where client calls server, and server calls the client back with a reply. However, can the server just call the client repeatedly? Or does the timer control act as the client-to-server caller?


Yo can use for calling javascript function

Registering Custom Script

from ScriptManager

http://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptBlock.aspx

For calling server side function use web services..


Actually, what I need to do requires "COMET", a form of "reverse AJAX". Is there an easy way to emplement COMET in ASP.Net? When the user clicks the "start" button, the server needs to begin "firing" pairs of numbers at the client at a steady rate (several times a second) until the user clicks the "stop" button.


Hi,

According to theclient life cycle, you can hook an event handler to theloadevent which will be fired every time an partial postback returns. Then invoke your graphical jscript function in it. For instance:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server"
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
<input id="time" />
</form
<script type="text/javascript">
function draw(){
var dt = new Date();
$get("time").value = dt.toString();
}

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
draw(); // invoke your graphical function instead
}
</script
</body>
</html>


Thanks, but I didnt get it what does this do ?


 <script type="text/javascript">
function draw(){
var dt = new Date();
$get("time").value = dt.toString();
}

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
draw(); // invoke your graphical function instead
}
</script>


This is a javascript function with no usefulness at all, just for demostration purpose. You need to invoke what you really need here.

I need the server to send a pair of numbers to the client each time it fires.


You can expose the method of sending numbers as a web service on the server.

Then invoke it at client side.

Please read this:

http://ajax.asp.net/docs/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx

Saturday, March 24, 2012

Call ASP.NET web service and return JSON using only html/javascript

I've implmented a pretty basic webservice as per below. I did a quick test in ASP.NET AJAX using the ScriptManager and it returned JSON-formatted data perfectly. I am now trying to do the same using just html/javascript with the XmlHttpRequest object.

Currently I've assigned the context-type to the XmlHttpRequest as is apparently required, and the webservice is "working", but only returning xml.Surprise

I'd really appreciate any help - or maybe even a better way to access the ASP.NET web service externally (i.e. outside of ASP.NET). Thanks.

PART A: ASP.NET Webservice snippet

[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ScriptingService : OrYxBaseWebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ScriptPersonRoleList GetActiveCategoryManagers() {
OrYxAppStatus myStatus = BFManager.GetInstance().CreateStatus(GetDefaultRequest());
return BFManager.ScriptingBF.GetActiveCategoryManagers(ref myStatus);
}
}

PART B: Index html

<html>
<head>
<title>Ajax Test Drive</title>
<script type="text/javascript" language="javascript">

function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
// http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("not good at all..");
}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}

http_request.onreadystatechange = confirmResponse;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-Type", "application/json");

http_request.send(parameters);
}

function confirmResponse() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
document.getElementById('databox').innerHTML = result;
alert('Response:\n\n' + result);
} else {
alert('There was a problem with the request.');
}
}
}

function getData() {
var url = 'http://localhost/TVScriptingWebService/TVScripting.asmx/GetActiveCategoryManagers';
var request = makePOSTRequest(url, "");
}
</script>

</head>
<body onload="getData()">
<div style="width: 600px; padding: 10px; border: 1px solid;" align="center">
Test page</div>
<br>
<div id="databox">
</div>
<br>
</body>
</html>

What format do you want data in now?


I am wanting JSON not XML.


use text/json rather than application/json


Thanks for the response, I tried adding the following lines, but they all still return only xml as the responseText

http_request.setRequestHeader('Content-Type','text/json');


Could i again confirm that the webservice is actually returning JSON data?


The only time I have seen the webservice returns JSON data is when its called from within ASP.NET AJAX pages using the ScriptManager - which I don't want to do because these services are ultimately going to be called from a php application..

I am trying to call it using using only javascript/html and cannot get it to return JSON - only xml

Environment: ASP.NET 2.0, AJAX ASP.NET RC1. Tested on IIS5.1 and IIS6

Thanks


Well again it could be an inadvertant policy issue where microsoft doesnt want people to use other products just like datatable which is not returned as webservice. But you can always convert xml to json.

Let me see your code for consuming page in .net


Hi naturehermit,

Thanks again. You're right I could parse the xml into Json within the client, however I think that would eliminate one of the main advantages of using JSON..Wink

I couldn't get it to work so I've implemented my own IHttpHandlerFactor and IHttpHandler classes which was pretty easy. They now intercept the webservice calls and check whether use my classes, which return JSON using the JavaScriptSerializer, or the generic WebServiceHandlerFactory().

Currently the flag I've decided on is if there is an "application/OrYxJson" within the Context-Type property of the request. If this property is set, JSON gets returned, otherwise you get good old SOAP.

Early days, but so far so good..


Good luck mate, let me know if i could be of any help. Its always good to share your experiences


Yep agreed and willdo. Thanks.


naturehermit:

What format do you want data in now?


?


Hi,

I ran into same issue where I specified in the webservice JSON and yet XML was returned. Anyway, I found ot that it actually returns JSON. Try running fiddler to intercept the response from the webservice and you'll see the JSON string. Ignore the "_type".

Thanks