How to call an ASP.NET WebMethod in a UserControl (.ascx)
Is it possible to place a WebMethod in an ascx.cs file (for a UserControl) and then call it from client-side jQuery code?
For some reasons I can't place the WebMethod code in an .asmx or .aspx file.
Example: In ArticleList.ascx.cs I have the following code:
[WebMethod]
public static string HelloWorld()
{
return "helloWorld";
}
In ArticleList.ascx file there I have the call to the WebMethod as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg开发者_如何学C;
},
url: "ArticleList.ascx/HelloWorld",
success: function(msg) {
alert(msg);
}
});
and the error from firebug is:
<html>
<head>
<title>This type of page is not served.</title>
How can I sucessfully call the server-side WebMethod from my client-side jQuery code?
WebMethod should be static. So, You can put it in the user control and add a method in the page to call it.
Edit:
You can not call a web method through a user control because it'll be automatically rendered inside the page.
The web method which you have in the user control:
public static string HelloWorld()
{
return "helloWOrld";
}
In the Page class add the web method:
[WebMethod]
public static string HelloWorld()
{
return ArticleList.HelloWorld(); // call the method which
// exists in the user control
}
Your method needs to be in an .aspx (or I think .ashx or .asmx will work as well). Since it's actually making a new call to the web server, IIS has to handle the request, and IIS will not respond to calls to .ascx files.
You cannot call a method directly in a user control using Jquery Ajax.
You can try one of the following approaches though:
Set the URL to
PageName.aspx?Method=YourMethod
or maybe add some other restrictions so you know which user control should execute the method. Then in your user control you can check for the existance of your restrictions in the querystring, and execute the given method.You can just use client callback to execute some method, if you need to do something async. in the GetCallbackResult in the page, you can find the control that caused the callback, and pass the request with its arguments to the control.
I came across this issue and used a combination of Dekker, Homan, and Gruber's solutions. All credit goes to them.
I needed to be able to modify the Session when a user clicked a check box. Since the page method has to be static its limited in what you can do inside it and I couldn't modify the Session. So I used jQuery to call a static method in the parent page of the user control that had call a web service method that did the work I needed.
User control's Javascript .ascx file
function chkSelectedChanged(pVal) {
//called when user clicks a check box
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{ "p1":' + pVal+' }',
url: "ParentPage.aspx/StaticPageMethod",
success: function (msg) {
//alert('it worked');
},
error: function (msg) {
alert('boom' + msg);
}
});
}
Parent Page Code Behind .aspx.cs file
[WebMethod]
public static void StaticPageMethod(string pVal)
{
var webService = new GridViewService();
webService.GridCheckChanged(pVal);
}
Web service .asmx
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class GridViewService : System.Web.Services.WebService
{
[WebMethod]
public void GridCheckChanged(string pVal)
{
//Do Work
}
}
You can do it like that in your Webmethod
Dim uc As UserControl = New UserControl()
Dim objSummarycontrol As SummaryControl = uc.LoadControl("~/Controls/Property/SummaryControl.ascx")
Dim propertyId As String = SessionManager.getPropertyId()
objSummarycontrol.populateTenancyHistory(propertyId)
You can't access WebMethod from user control but you can perform your functionality.
- Create one simple webpage(aspx).
- Write webmethod in webpage(aspx.cs).
- Access method from webpage.
Control registration at aspx :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomerRequirements.aspx.cs" EnableViewState="true" Inherits="Bosch.RBNA.CustomerRequirementsServerWeb.Pages.CustomerRequirements" %>
<%@ Register TagPrefix="pp" Src="~/Pages/PeoplePicker.ascx" TagName="PeoplePicker"%>
Control usage in aspx :
<div class="form-group">
<label for="exampleInputPassword1">Contact to get permisson</label>
<pp:PeoplePicker runat="server" ID="peoplePicker" ClientIDMode="Static"></pp:PeoplePicker>
</div>
jQuery AJAX Call :
$.ajax({
type: "POST",
url: CustomerRequirements.aspx/GetPeoplePickerData + "?SearchString=" + searchText + "&SPHostUrl=" + parent.GetSpHostUrl() + "&PrincipalType=" + parent.GetPrincipalType() + (spGroupName? "&SPGroupName=" + spGroupName: ""),
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
parent.QuerySuccess(queryIDToPass, msg.d);
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
parent.QueryFailure(queryIDToPass);
}
});
Code behind method :
[System.Web.Services.WebMethod]
public static string GetPeoplePickerData()
{
try
{
return PeoplePicker.GetPeoplePickerData();
}
catch (Exception ex)
{
throw ex;
}
}
Code behind of Control :
[WebMethod]
public static string GetPeoplePickerData()
{
try
{
//peoplepickerhelper will get the needed values from the querystring, get data from sharepoint, and return a result in Json format
Uri hostWeb = new Uri("http://ramsqlbi:9999/sites/app");
var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, HttpContext.Current.Request.LogonUserIdentity);
return GetPeoplePickerSearchData(clientContext);
}
catch (Exception ex)
{
throw ex;
}
}
clyde No, because ascx controls don't represent a real URL that can be accessed from a client machine. They're purely server-side meant to embed in other pages.
What you might want to do is just have an aspx page that provides the same snippet of html you currently have in your ascx file. An aspx page doesn't necessarily need to provide a full html document ( etc.), it can just render the user control you're interested in.
We use this technique all the time with the ingrid plugin, which requires a callback url for the table contents.
精彩评论