用JQuery在客户端调用C#后台函数

来源:互联网 发布:php字符串反转函数 编辑:程序博客网 时间:2024/05/16 00:49

建立一个页面叫Test.aspx, 在Test.aspx.cs文件中有如下函数:

[csharp] view plaincopyprint?
  1. private void DeleteRec()
  2. {
  3. int ID= Request.Form["ID"].ToString().ToInteger();
  4. //客户端发过来的参数
  5. int UserID = Request.Form["UserID "].ToString().ToInteger();
  6. //客户端发来的用户名参数
  7. UserBO lObjUserBO = new UserBO ();
  8. lObjUserBO .DeleteUser(ID, UserID );
  9. }


在Page_Load事件中调用上面函数:

[csharp] view plaincopyprint?
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!Page.IsPostBack)
  4. {
  5. #region Ajax methods
  6. if (Request.Form["MethodName"] =="DeleteR")
  7. // 该参数指明是从客户端发来的调用参数
  8. {
  9. DeleteRec();// 调用删除记录的函数
  10. return;
  11. }
  12. #endregion
  13. }
  14. }


在客户端Test.aspx页面写如下代码:

[html] view plaincopyprint?
  1. <aid="adelete"href="#">删除</a>

用下面的函数实现删除功能:

[javascript] view plaincopyprint?
  1. $('#adelete').click(function()
  2. {
  3. var dataToSend={ID:ID,MethodName:'DeleteR',UserID :UserID };
  4. var options =
  5. {
  6. url: '<%=ResolveUrl("~/Test.aspx") %>?x=' +new Date().getTime(),
  7. data: dataToSend,
  8. dataType: 'JSON',
  9. type: 'POST',
  10. success: function (response) {
  11. window.location.href='<%=ResolveUrl("~/Test1.aspx")%>/'+ID;
  12. //删除成功后跳转到新页面
  13. }
  14. }
  15. $.ajax(options);
  16. });