Home > AJAX, ASP.NET, jQuery > Calling web service using jQuery

Calling web service using jQuery

html
<input type =”text” id=”name” />

<input type =”button” id=”btn” value=”click me” />

<div id=”test”>    </div>

JS

$(document).ready(function () {
$('#btn').click(function (event) {
$.ajax({
type: "POST",
url: "WebService.asmx/LoadControl",
data: "{'name': '" + $('#name').val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
$('#test').html(result.d);
}

function AjaxFailed(result) {
$('#test').html(result.status + ' ' + result.statusText);
}

});

Web Service

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

[WebMethod]

public string LoadControl(string name)
{
return ViewManager.RenderView("Test.ascx");
}}

View Manager

public class ViewManager

{
public static string RenderView(string path)
{
return RenderView(path, null);
}

public static string RenderView(string path, object data)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl(path);

if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");

if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("View file: " + path + " does not have a public Data property");
}
}

pageHolder.Controls.Add(viewControl);

StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);

return output.ToString();
}
}

 

Advertisement
Categories: AJAX, ASP.NET, jQuery
  1. aamir saeed
    March 4, 2011 at 12:41 pm | #1

    thank you so much it was handy.

  2. aamir saeed
    March 4, 2011 at 12:42 pm | #2

    thankyou so much. Excellenet article.

  3. aamir saeed
    March 4, 2011 at 12:42 pm | #3
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.