如何将对象传递给ajax中的处理程序

时间:2014-04-04 09:55:52

标签: c# javascript jquery ajax

我需要在javascript中创建一个对象并将其传递给处理程序

var EducationalInstitute = new Object();
EducationalInstitute.InstituteId = iInstituteId;
EducationalInstitute=Name;

现在我需要在ajax中传递它

 $.ajax({
        url: "../Handlers/DeleteEducationalInstitutes.ashx",
        dataType: "json",
        responseType: "json",
        cache: "false",
        data: { EducationalInstitute: JSON.stringify(EducationalInstitute) },
        success: DeleteEISuccess
    });

问题是我不知道如何在处理程序中将其作为对象!

var Institute = context.Request.QueryString["EducationalInstitute"];
EducationalInstitute educationalInstitute = (EducationalInstitute)new JavaScriptSerializer().DeserializeObject(Institute);

我为学院获得的价值是{"InstituteId":"1"}

类定义是

 public class EducationalInstitute
    {
        [DataMember]
        public int InstituteID { get; set; }
        [DataMember]
        public string InstituteName { get; set; }
        [DataMember]
        public string Zone { get; set; }
    }

我收到错误

{"Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'namespace.BusinessEntities.EducationalInstitute'."}

2 个答案:

答案 0 :(得分:1)

我认为这是您在javascript中创建模型的方式:

var model= {InstituteId: iInstituteId, InstituteName: iName};

iInstituteId& iName是您在客户端代码

中创建的变种
    $.ajax({
            url: "../Handlers/EducationalInstitutes.ashx",
            dataType: "json",
            responseType: "json",
            cache: "false",
            data: {EducationalInstitute:JSON.stringify(model)},

以下是一个例子:http://geekswithblogs.net/pabothu/archive/2011/05/21/passing-a-complex-json-object-to-ashx-and-reading-it.aspx

答案 1 :(得分:0)

我就这样做了

var Team = { EducationalInstitute: EducationalInstitute, Location: "Chennai", Mentor: Mentor, TeamDescription: TeamDescription, TeamId: 1, TeamLeader:"",TeamLogo: TeamLogo, TeamName: TeamName };

调用Ajax

 $.ajax({
            url: "../Handlers/CreateTeam.ashx",
            dataType: "json",
            responseType: "json",
            data: {Team:JSON.stringify(Team)},
            success: createTeamSuccess,
            error:createTeamError
            });

C#代码

Team team=new Team();
var teamObject = context.Request.QueryString["Team"];
team = (Team)new JavaScriptSerializer().Deserialize(teamObject,typeof(Team));