我在 C# 中有一个 Person 类。
我希望能够在我的 js 中做:
var p = new Person();
稍后我通过 jQuery Ajax 将 p 对象发送到 ashx
有哪些库(jQuery?xxx?)可以帮助我做到这一点?
我知道 Ajaxtookit 有一个属性:ScriptService
但我不确定这个解决方案有多好。
最佳答案
您可以将 ASPX PageMethods 与 jQuery 结合使用。因此,通过定义模型开始在服务器上工作:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
然后你可以在某个 aspx 页面 (/foo.aspx
) 中定义一个页面方法:
public partial class _Foo : System.Web.UI.Page
{
[WebMethod]
public static string SavePerson(Person p)
{
// do some processing with the person
return "Hello World";
}
}
最后调用这个页面方法:
var p = {
firstName: 'John',
lastName: 'Smith'
};
$.ajax({
url: '/foo.aspx/SavePerson',
type: 'POST',
contentType: 'application/javascript; charset=utf-8',
data: JSON.stringify(p),
success: function(result) {
alert(result.d);
}
});
此处说明的 JSON.stringify 方法内置于现代浏览器中。如果您需要支持旧版浏览器,您可以包含 json2.js脚本到您的页面。
更新:
根据评论部分的要求,您可以设计一个通用的 ASHX 处理程序来接收此请求,进行一些处理并返回 JSON 响应:
public class Foo : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var serializer = new JavaScriptSerializer();
using (var reader = new StreamReader(context.Request.InputStream))
{
Person person = (Person)serializer.Deserialize<Person>(reader.ReadToEnd());
// do some processing with the person
}
context.Response.ContentType = "application/json";
var result = serializer.Serialize(new { data = "Hello World" });
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
和请求:
var p = {
firstName: 'John',
lastName: 'Smith'
};
$.ajax({
url: '/foo.ashx',
type: 'POST',
data: JSON.stringify(p),
success: function(result) {
alert(result.data);
}
});
关于c# 类到 Js 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770547/