[英]Calling a c# method trough Ajax without using static methods
我正在一个必须使用ajax的网站,并且想知道是否存在一种从服务器端调用方法而不将方法设置为静态的方法。 我对此进行了研究,但是发现的每个示例都将方法设置为静态,并且想知道是否可以通过使用静态来实现,这是我的代码
Ajax代码:
function GetAddColour(id, Name) {
var dataValue = { "id": id, "Name": Name }
$.ajax({
url: "AddColour.aspx/btnAddColour",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
C#代码:
[WebMethod]
public static void btnAddColour(int id, string Name)
{
//do things to add colour
}
有没有静态方法的方法,我也不能使用更新面板。
使用ASP.NET AJAX页面方法,您可以访问Session
对象,因此,如果将登录的用户名存储在Session["User"]
,则可以执行以下操作:
后台代码:
[WebMethod(EnableSession = true)]
public static string GetLoggedInUserName()
{
return HttpContext.Current.Session["User"].ToString();
}
标记:
$.ajax({
url: "AddColour.aspx/GetLoggedInUserName",
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.hasOwnProperty("d")) {
// Need to de-reference the JSON via the .d
alert(result.d);
}
else
{
// No .d; no de-reference necessary
alert(result);
}
},
error: function (e) {
alert(JSON.stringify(e));
}
});
注意:
.d
语法是Microsoft在ASP.NET AJAX的ASP.NET 3.5版本中.d
的反XSS保护。 因此检查以查看.d属性是否存在。
假设您使用的是Web表单而不是ASP.Net MVC,则可以创建一个*.ashx
HttpHandler。 它就像一个*.aspx
页面,但简单得多。 您的背后代码仅需实现IHttpHandler
接口(1个方法, ProcessRequest()
和1个属性IsReusable
)。 如果您需要访问会话状态,则还需要“实现”(使用错误的名称,因为它们都是没有实现的标记接口),或者是IReadonlySessionState
(只读访问)或IRequiresSessionState
(读/写访问)。
但是,您要负责这里几乎所有的事情,从汤到坚果。 您可以随心所欲地返回JSON,二进制图像数据。
修改您的数据值对此。
var dataValue = "{id :'" + id + ", Name :'"+ Name "'}" ;
其中id和name是两个分别具有整数和字符串值的变量。 确保id为整数,如果不是,则将其更改为Number(id)
Javascript:
function GetAddColour(eid, eName) {
var id = Number(eid);
var Name = eName;
var dataValue = "{id :'" + id + ", Name :'"+ Name "'}" ;
$.ajax({
url: "AddColour.aspx/btnAddColour",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
并且您的C#网络方法应该是
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void btnAddColour(int id, string Name)
{
// Your code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.