A tool for convert .net WebService(.asmx) to jquery AJAX code.

2013-06-25

.Net WebService is something I find very convenience, service side of lots project on hand has adopted this technique.

Lately ajax has been used frequently. I've been thinking, how dose client side(.html) to call web service(.asmx) more faster.

Therefore "NO2AjaxGenerator" has been created.

The advantages as following:

1. Fastly generate javascript code to call the .Net WebService(.asmx).

2. Fully support intelligent sense of your customize object under javascript side on Visual Studio 2012.

3. Easy to use, passing parametes through JSON.

4. Having same experience in Javascript like coding in C#.

Let's check out the sample . this Server side .net WebService(.asmx) :

customize object - User.cs :

namespace SimpleUserService
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public System.DateTime Birth { get; set; }
    }
}


Web Service(UserService.asmx):


using System;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services;
 
namespace SimpleUserService
{
    /// <summary>
    /// Summary description for UserService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class UserService : WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public User[] GetAllUsers()
        {
            var res = new List<User>();
            for (int i = 1; i <= 10; i++)
            {
                res.Add(new User
                    {
                        Id = i,
                        Birth = new DateTime(2012, 1, 1).AddDays(i),
                        Name = "User " + i
                    });
 
            }
 
            return res.ToArray();
 
        }
 
 
 
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public User AddUser(User user)
        {
            user.Id = 1946;
            return user;
        }
    }
 
}

We want JSON to be the output, therefore extra red parts is necessary.
the reference: http://www.dotblogs.com.tw/junegoat/archive/2012/10/08/c-sharp-dot-net-web-service-by-json-test-with-jquery.aspx


We can see a very normal we service after execution:
2013-06-17_144223_thumb[2] 
the path : http://localhost:10020/UserService.asmx


We download No2AjaxGenerator at https://github.com/donma/JqueryAjaxGenerator
After execution, we can see

Image

1 : Enter path of WebService.
2 : Sset up service related to path of .html(clinet) , ensure .html can call the service path.
3 : Methods and all objects that used in web service will be generated after pressing “Analyze” button.
4 : All objects in WebService.
5 : All methods in WebSercive.
6 : Preview of generated code.
2013-06-17_144918_thumb[1]
7 : Save the code for generating javascript. In this case, I save it for “jq.data.js”.



Let's see how to use the “jq.data.js”


Step 1 : including the jquery and jq.data.js


<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="jq.data.js"></script>
</head>

Step2: You can call the methods "GetAllUsers"  and  "AddUser" directly .

Let's see how simplify the code can be


<body>
 
    <div id="div_allusers" style="background-color: #EEFCFC">
    </div>
 
    <div id="div1" style="background-color: #FFCDE5">
 
        <input type="button" value="Add User" onclick="btnaddUser_click()"></input>
    </div>
    <script>
   1:  
   2:  
   3:         //測試 GetAllUsers() 是否運作正確
   4:         //Sample for GetAllUsers function and get User[].
   5:         var allUsers = GetAllUsers();
   6:         for (var i = 0; i < allUsers.length; i++) {
   7:  
   8:             $('#div_allusers').append(allUsers[i].Id + "," + allUsers[i].Name + "," + ConvertToDate(allUsers[i].Birth).toString() + "<br />");
   9:  
  10:         }
  11:  
  12:         //測試 AddUser(UserObject) 傳入物件且回傳物件
  13:         //Sample for AddUser(UserObject) function and get result.
  14:         function btnaddUser_click() {
  15:  
  16:             var userA = new User();
  17:  
  18:             userA.Name = "I'm userA.";
  19:  
  20:             userA.Birth = new Date("2012/12/21");
  21:  
  22:             var res = AddUser(userA);
  23:  
  24:             alert("Id:" + res.Id + "," + "Name:" + res.Name + "," + "Birth:" + ConvertToDate(res.Birth).toString());
  25:  
  26:         }
  27:  
  28:         //轉換 .net Datetime ojbect 成為javascript 用的Date 物件
  29:         //Convert .net Datetime object to javascript Date
  30:         function ConvertToDate(srcDate) {
  31:             var ms = parseInt(srcDate.match(/\((\d+)\)/)[1]);
  32:             return new Date(ms);
  33:  
  34:         }
  35:  
  36:     
</script>
 
</body>



Result:


2013-06-17_153436_thumb[1]


(Passing all parameters by JSON format.)


Declare a User object in Visual Studio 2012, and support intelligent sense.


2013-06-17_150235_thumb[1]


Including all properties in User object.


2013-06-17_150333_thumb[3]


While you call the methods, the parameters is the same with WebService(.asmx).



2013-06-17_150446_thumb[2]


Give it a try, see if developing is going faster.


1. About time problem, if web service return objects type is DateTime, use function to convert.



//轉換 .net Datetime ojbect 成為javascript 用的Date 物件
 
//Convert .net Datetime object to javascript Date
function ConvertToDate(srcDate) {
    var ms = parseInt(srcDate.match(/\((\d+)\)/)[1]);
    return new Date(ms);
}

No enclosed on generating for retain the elasticity.


2. Each function comes with successFunc and errorFunc, ignore it if no need.


3. Please see the reference for completed example and instruction => https://github.com/donma/JqueryAjaxGenerator



THANKS for Interpreter: EYNA


當麻許的超技八 2014 | Donma Hsu Design.