Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Sharing data between JavaScript and ASP.NET C#

  • 02-12-2010 11:01am
    #1
    Registered Users, Registered Users 2 Posts: 539 ✭✭✭


    Hi guys.

    Im doing project where I will need to display data on web page using JavaScript. Im using Raphael JS library for drawing graphics. I am stuck on the bit where I need to retrieve data from my server (Server is going to be retrieving data from another source). I am using ASP.NET and C#. So, is Ajax the only way to do this? Not familiar with Ajax at all and I am thinking would it be possible to push data from server to client and trigger an event where I will be updating graphics (I cant have Threads in JavaScript so I guess there is no way that I could be udating graphics constantly, lets say every second, or maybe I'm wrong?).

    Thanks in advance.


Comments

  • Registered Users, Registered Users 2 Posts: 981 ✭✭✭fasty


    AJAX is the way to go here. You make GET or POST requests via Javascript and update the page based on those results.

    It's hard to give specifics though, I don't really know the library you're using but I've done a lot of JQuery -> ASP.Net MVC stuff myself and it's painless enough.


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    You can use either webservices or page methods easily enough either.


  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    Hi.
    Had a look at webservices and page methods and couldn't find an example that I could use. The same with Ajax. I can find examples where something on a page is updated once a button is pressed but that is not what I am looging for. I'm trying to update graphics on client side every 2 or 3 seconds. I will basically have multiple JavaScript objects on client side made using Raphael JS library. I will need to update these objects from server side every second once the page is open. Something like calling JavaScript method from C# codebehind would be the best solution but I am pretty sure this is not possible (JavaScript being executed on clients machine).
    Thanks.


  • Registered Users, Registered Users 2 Posts: 2,494 ✭✭✭kayos


    Think your approaching this the wrong way around. You need to make the Javascript call to the web server to get the data every Xseconds. So go google setInterval(). Add to that the example you've seen of page methods or web services and you have your solution.


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    Familiarise yourself with something like jQuery, Webservices + JSON or similar.
    function GetUpdates(){
        $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          url: "WebService.asmx/WebMethodName",
          data: "{}",
          dataType: "json",
          success: function(data){ alert($.parseJSON(data.d)); }
        });
    }
    
    setInterval('GetUpdates()',5000);
    


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    Thanks for all the replies guys.
    Haven't had much time to look at this since I last posted here.
    Giblet, you have an example there of JavaScript code. Any chance you could point me to page where it explains how I would get this working on both sides??
    By the way I don't know much about C#, JavaScript jQuery or JSON :(

    Thanks


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    Ok, using Visual Studio, create a new webservice

    It should look something like this, the below will take in a JSON object passed by the data attribute of your ajax call, deserialise to an object, then do some work, then serialise again to return to your client. Then using the success function of the ajax call, alerts the returned data. (.NET will create a subobject called d which contains your data)

    JSON is just JavaScript Object Notation, it's a lightweight container which is handy for this purpose. I would read up on anything you don't understand, there are better guides out there than I can give.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Text;
    using System.Data;
    
    namespace MyApp.WebService
    {
        /// <summary>
        /// Summary description for HelloWorld
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class HelloWorld : System.Web.Services.WebService
        {
    
            [WebMethod(true)]
            public string HelloWorld(string json)
            {
                MyObject myObject = json.FromJson<MyObject>();
                myObject.DoSomething();
                return myObject.ToJSON();           
            }
    }
    }
    

    I use a JSON helper method to serialise the javascript.
    Here is that class, which you should create in your solution
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Script.Serialization;
    
    
    namespace MyApp
    {
        public static class JSONHelper
        {
            /// <summary>
            /// Converts an object to a JSON string.  This is an extension method for any object.
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string ToJSON(this object obj)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Serialize(obj);
            }
    
            /// <summary>
            /// Converts to a suitable object from a JSON string.  
            /// This is an extension method for any object. the object should 
            /// reflect the underlying structure of the data
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static T FromJson<T>(this object obj)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Deserialize<T>(obj as string);
            }
        }
    }
    
    
    


  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    Great help Giblet. Thanks a lot.
    I'm still lost where does my JavaScript code go but I will try looking up about Web Services.
    Does anybody know any good site where I could look that up? :)

    Thanks


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    Throw it into a <script>tag in your html page, or import from a seperate js file using <script src="file.js"></script>


  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    Ok, I think I am very close but not there yet.

    Where am I going wrong? And how do you run the service? (I'm not very familiar with visual studio or ASP.NET)

    Here is the code that I have
    Service.asmx.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Text;
    using System.Data;
    
    namespace FinalProject
    {
        /// <summary>
        /// Summary description for HelloWorld
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class HelloWorld : System.Web.Services.WebService
        {
    
            [WebMethod(true)]
            public string HelloWorldy(string json)
            {
                MyObject myObject = json.FromJson<MyObject>();
                myObject.DoSomething();
                return myObject.ToJSON();
            }
    }
    }
    

    MyApp.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Script.Serialization;
    
    namespace FinalProject
    {
        public static class JSONHelper
        {
            /// <summary>
            /// Converts an object to a JSON string.  This is an extension method for any object.
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string ToJSON(this object obj)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Serialize(obj);
            }
    
            /// <summary>
            /// Converts to a suitable object from a JSON string.  
            /// This is an extension method for any object. the object should 
            /// reflect the underlying structure of the data
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static T FromJson<T>(this object obj)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Deserialize<T>(obj as string);
            }
        }
    }
    

    MyObject.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace FinalProject
    {
        public class MyObject
        {
            int m_value=0;
            public void DoSomething()
            {
                m_value++;
            }
            public int GetValue()
            {
                return m_value;
            }
        }
    }
    

    HTMLPage1.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
    <script type="text/javascript">
        function GetUpdates() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Service1.asmx/HelloWorld",
                data: "{}",
                dataType: "json",
                success: function (data) { alert($.parseJSON(data.d)); }
            });
        }
        setInterval('GetUpdates()', 5000);
    </script>
    <p>Testing This Page</p>
    </body>
    </html>
    

    Whenever I debug the HTMLPage1 the code never goes near the alert($.parseJSON(data.d)) line.
    What am I missing there?

    Again, Thanks guys


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    Get firebug for firefox, and check the net panel and console to see what's being request. Also, set debug points in your Webservice.


  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    Ok, starting to get somewhere.
    When looking at my HTMLPage1.html in firefox with firebug I can see that the POST request is being sent to my web service. I'm getting 500 internal server error though. I have a feeling that it is because my web service is not running. How would I make it run in VS2010? If I right click on the Service1.asmx and click View in Web Browser I get this error
    Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. 
    
    Parser Error Message: Could not create type 'Project.Service1'.
    
    Source Error: 
    
    
    Line 1:  <%@ WebService Language="C#" CodeBehind="Service1.asmx.cs" Class="Project.Service1" %>
    
    Source File: /Service1.asmx    Line: 1 
    

    Tried googling this but I'm getting nowhere...


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    Have you configured the project to work in .NET 3.5?


  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    Ok, I found a solution that I was looking for. It's very similar to what you where suggesting except it's not using JSON. I will look into maybe changing that in the future but I will leave it for now. This is the article that I was working from http://msdn.microsoft.com/en-us/library/bb532367.aspx

    Great help Giblet. Would not have found the article without your help.
    Thanks


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    but43r wrote: »
    Ok, I found a solution that I was looking for. It's very similar to what you where suggesting except it's not using JSON. I will look into maybe changing that in the future but I will leave it for now. This is the article that I was working from http://msdn.microsoft.com/en-us/library/bb532367.aspx

    Great help Giblet. Would not have found the article without your help.
    Thanks
    Ah cool, Maybe you had a small problem with your JSON class or something.

    For your example, try something like this

    string x = "{'name':'Tom'}";
    return x;

    You won't need any JSON serialisation stuff then, you can read that returned string as an object after you parse it in your javascript the same way I did above.


  • Registered Users, Registered Users 2 Posts: 539 ✭✭✭but43r


    So I have got the Web service working from the previous example. Now I'm having another problem. From that example I can call 1 method from my Web Service but I have no Idea how would I go about calling more than 1 method.

    Here is the JavaScript code from that example.
    var helloWorldProxy;
    
    // Initializes global and proxy default variables.
    function pageLoad()
    {
        // Instantiate the service proxy.
        helloWorldProxy = new Samples.Aspnet.HelloWorld();
    
        // Set the default call back functions.
        helloWorldProxy.set_defaultSucceededCallback(SucceededCallback);
        helloWorldProxy.set_defaultFailedCallback(FailedCallback);
    }
    
    
    // Processes the button click and calls
    // the service Greetings method.  
    function OnClickGreetings()
    {
        var greetings = helloWorldProxy.Greetings();
    }
    
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result)
    {
        var RsltElem = document.getElementById("Results");
        RsltElem.innerHTML = result;
    }
    
    // Callback function invoked when a call to 
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) 
    {
        if(error !== null) 
        {
            var RsltElem = document.getElementById("Results");
    
            RsltElem.innerHTML = "An error occurred: " + 
                error.get_message();
        }
    }
    
    if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    The problem is that the result is received in SucceededCallback method. How would I modify the code above to be able to call more than 1 method??

    Thanks in advance...


  • Registered Users, Registered Users 2 Posts: 11,989 ✭✭✭✭Giblet


    You can do it through jQuery easily enough using the $.ajax() function.
    You can call different methods and set a callback for each one rather than hooking up a global.


Advertisement