i have the following code: (simplified for readability)
C#
foreach(DataRow 开发者_如何学GodRow in myDS.Tables[0].Rows){
Company myCompany = new Company();
myCompany.id = int.Parse(dRow["id"].ToString());
Companies.Add(myCompany);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(Companies));
Response.End();
jQuery
$.getJSON('ajax.aspx?what=' + $('input[name="what"]').val() + '&where=' + $('input[name="what"]').val(), function (data) {
$.each(data, function (key, val) {
var myCompany = new function () {
this.id = val.id;
}
Companies.push(myCompany);
});
});
Now, i have another object in the C# code, which is named Cities
and i would like to return it in the same request.
something like
Response.Write(serializer.Serialize(Companies));
Response.Write(serializer.Serialize(Cities));
Response.End()
and offcourse parse it on the Client side.
how can i do something like that?
You could wrap the two properties into an anonymous object:
var result = new { Cities = Cities, Companies = Companies };
Response.Write(serializer.Serialize(result);
Response.End();
Or if you are using some old .NET version which doesn't support anonymous objects you could define a wrapper class:
public class Wrapper
{
public IEnumerable<Cities> Cities { get; set; }
public IEnumerable<Company> Companies { get; set; }
}
and then:
Wrapper result = new Wrapper();
wrapper.Cities = Cities;
wrapper.Companies = Companies;
Response.Write(serializer.Serialize(wrapper);
Response.End();
Also fix your AJAX call as you are not properly url encoding your parameters:
var data = {
what: $('input[name="what"]').val(),
where: $('input[name="what"]').val()
};
$.getJSON('ajax.aspx', data, function (data) {
$.each(data.Companies, function (index, val) {
var myCompany = new function () {
this.id = val.id;
}
Companies.push(myCompany);
});
});
You need to create Object
containing both collections like this:
{
"Cities": { ... Cities Collection ... },
"Companies": { ... Companies Collection ... }
}
So create one Object like
[Serializable]
public class Output {
Collection<City> cities;
Collection<Company> companies;
}
then will this object with data and output it
精彩评论