您的位置:首页 > Web前端 > JQuery

jQuery中使用getJSON方法调用C#的后台方法

2012-02-29 00:36 661 查看
首先创建一个JSONHelper.css类在创建两方法一个用来返回getJSON的返回值,另外一个用来序列化对象·····

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text;
//序列
using System.Web.Script.Serialization;
namespace SCJob.WebUI.JsonHelper
{
public class JSONHelper : System.Web.UI.Page
{

/// <summary>
/// 返回JSON数据到请求的函数
/// </summary>
/// <param name="callback">回调参数</param>
/// <param name="data">序列的JSON字符串</param>
/// <param name="Response">与Page对象关联的HttpResponse对象</param>
public void ReturnJSON(string callback, string data, HttpResponse Response)
{
string result = string.Format("{0}({1})", callback, data);
Response.Expires = -1;
Response.Clear();
Response.ContentEncoding = Encoding.UTF8;
Response.ContentType = "application/json";
Response.Write(result);
Response.Flush();
Response.End();
}
/// <summary>
/// 转换为JSON数据
/// </summary>
/// <param name="obj">要转换为JSON数据的对象</param>
/// <returns>返回JSON字符串</returns>
public string ToJSON(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
}
}


$('#btnAllrefresh').click(function () {
$.getJSON('JobList.aspx?jsoncallback=?&operate=allRefresh', function (data) {
if (data.error) {
$.message(data.error, { title: '系统提示', icon: 'fail' });
//这里的$.message方法是自己写的函数用来做用户体验的
//自己可以用alert方法data.error获得后台代码的返回值error为返回的json串中的键
return;
}
if (data.message) {
$.message(data.message, { title: '操作提示', icon: 'fail' });
}
})
});


上面的代码和下面的这两段代码都是前台的jquery代码按钮的点击事件

$.getJSON("JobList.aspx?jsoncallback=?", { operate: 'deleteJob', jobID: jobID }, function(data) {
if (data && data.error) {
$.message(data.error, { title: '系统提示', icon: 'fail' });
return;
}
$.anchorMsg('删除职位成功');
$('#row' + jobID).next('.getlist_line').andSelf().remove();
})


private JSONHelper jsonHelper = new JSONHelper();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["operate"] != null)
{
string operate = Request.QueryString["operate"];
//删除职位信息
if (operate == "deleteJob")
{
if (Request.QueryString["jobID"] != null)
{
DeleteJob(int.Parse(Request.QueryString["jobID"]));
}
}
}
}
/// <summary>
/// 删除职位
/// </summary>
/// <param name="JobId">职位编号</param>
public void DeleteJob(int JobId)
{
SC_CpApplyJob job = new SC_CpApplyJob();
job = jobs.GetEntity(JobId);
string message = "{\"succee\":\"OK\"}";
try
{
//执行删除操作
jobs.DelEmpty(job);
}
catch (Exception ex)
{
//自己写的json字符串用来作为返回值 方便前台使用
message = "{\"error\":\"删除失败\"}";
throw;
}
finally
{
//调用自己创建的类中的方法  参数说明:Response当前的HttpResponse对象主要用来输出到前台中的数据有用
jsonHelper.ReturnJSON(Request.QueryString["jsoncallback"], message, Response);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: