Monday, September 6, 2010

Exposing DTO to javascript in ASP.NET...

This post is a continuity from my previous post related to Calling a webservice from javascript in ASP.NET 2.0. Fundamentally it's sharing the same concept. This time I've written the code in ASP.NET 3.5 (Visual Studio 2008). There's no prerequisite required compare to when I did it in ASP.NET 2.0 (Visual Studio 2005).

Once I knew how to call a webservice from javascript in ASP.NET (regardless of version). I've search google to check whether it's possible to pass an object as a parameter to webservice method. Indeed it is possible to do that, but I must make sure that the object should be simple enough without any business logic and with limited behaviour. The object known as Data Transfer Object or in short DTO. Now here's the step by step on how to do it.

1) Using Visual Studio 2008, create new web site. Select ASP.NET Web Site.

2) To create DTO object, add new class under App_Code folder. Lets name it as Student. Paste the code below.
    using System;

///
/// Summary description for Student
///

public class Student
{
public Student()
{
}

public string Id
{
get;
set;
}

public string Name
{
get;
set;
}
}
3) Create new webservice call MyWebService. Add System.Web.Script.Services namespace then add GenerateScriptType and ScriptService attribute to the webservice class. Notice that what I did here is almost the same as my previous post. The only extra code is at line 7 which is to expose Student class to javascript.
    ...
using System.Web.Script.Services;

///
/// Summary description for MyWebService
///

[GenerateScriptType(typeof(Student))]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : System.Web.Services.WebService
{
...
}
4) Add two methods call GetStudents and TestSubmit. GetStudents method will return a list of students to the caller. Since I want to return it as a JSON object, I've set the ResponseFormat to JSON.
    ...
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<Student> GetStudents()
{
var students = new List<Student>();

for (int x = 0; x < 10; x++)
{
students.Add(new Student
{
Id = x.ToString(),
Name = "Name" + x.ToString()
});
}

return students;
}

[WebMethod]
public string TestSubmit(Student student)
{
return String.Format("You've submitted Student object with Id: {0} and Name: {1}", student.Id, student.Name);
}
5) Go to Default.aspx, add ScriptManager (again another same step as my previous post in ASP.NET 2.0).
    ...
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference InlineScript="true" Path="~/MyWebService.asmx" />
</Services>
</asp:ScriptManager>
...
6) Now add the html control
    ...
<div>
<input id="btnLoad" type="button" value="Get Students" onclick="javascript:btnLoad_Click();" />

<input id="txtId" type="text" /><input id="txtName" type="text" />
<input id="btnSubmit" type="button" value="Submit" onclick="javascript:btnSubmit_Click();" />

<table id="myTable" border="1" cellpadding="1" cellspacing="1"></table>
</div>
...
7) and the javascript
    ...
<script language="javascript" type="text/javascript">
function btnLoad_Click()
{
try
{
MyWebService.GetStudents(OnGetStudentsComplete);
}
catch(e)
{
alert("error " + e);
}
}

function OnGetStudentsComplete(result)
{
var htmlVal = "";

for(var x=0; x<result.length; x++)
{
htmlVal += "<tr><td>" + result[x].Id + "</td><td>" + result[x].Name + "</td></tr>";
}

$get("myTable").innerHTML = htmlVal;
}

function btnSubmit_Click()
{
try
{
var stu = new Student();
stu.Id = $get("txtId").value;
stu.Name = $get("txtName").value;

MyWebService.TestSubmit(stu, OnTestSubmitComplete);

var htmlVal = $get("myTable").innerHTML;
htmlVal += "<tr><td>" + stu.Id + "</td><td>" + stu.Name + "</td></tr>";
$get("myTable").innerHTML = htmlVal;
}
catch(e)
{
alert(e);
}
}

function OnTestSubmitComplete(result)
{
alert(result);
}
</script>
Now I have a web site that can call a webservice and passing an object as a parameter via javascript.

No comments:

Post a Comment