2009-03-11 6 views
0

Les gars, je ne peux pas sembler obtenir la sérialisation de l'objet fonctionne correctement clientide pour mon application? Lorsque j'utilisais la méthode getJSON() dans jQuery avec une réponse de type mime text/json (sérialisé à l'aide de la librairie JSON.Net), ça fonctionnait bien, mais dès que je l'avais déplacé vers une requête ajax() (donc je pourrait poster mon code dans webmethods sur ma page) son tombé. Toutes les idées seraient grandement appréciées.Comment formater correctement les réponses JSON (pour jQuery) à partir d'ASP.NET AJAX?

Edit: Je suis en utilisant le framework 2.0, pas 3.5

Mon javascript ressemble à ceci: (. Nb sa page, pas un webservice)

function companySearch(txt) 
    { 
     $("#<%= divCompanyResult.ClientID %>").hide(); 
     $("#<%= divCompanyResult.ClientID %>").html(""); 

     var strCompanySearch = $("#<%= tbCompanySearch.ClientID %>").val(); 

     $.ajax 
     ({ 
      type: "POST", 
      url: "Home.aspx/GetCompanies", 
      contentType: "application/json; charset=utf-8", 
      datatype: "json", 
      data: "{name: '" + strCompanySearch + "'} ", 
      success: companySearchSuccess, 
      error: onError 
     }); 

     return (true); 
    } 

    function companySearchSuccess(response) 
    { 
     $.each(response, 
      function(i, company) 
      { 
       $("#<%= divCompanyResult.ClientID %>").prepend(company.Name + "<br />"); 
      }); 

     $("#<%= divCompanyResult.ClientID %>").slideDown(1000); 
    } 

Et ma page .ASPX, regards comme ceci:

[WebMethod] 
    public static Company[] GetCompanies(string name) 
    { 
     Company[] companies = Company.FindCompanies(name); 

     return companies; 
    } 

Et l'objet de son retour:

[ActiveRecord] 
public class Company : ActiveRecordBase<Company> 
{ 
    private int iD; 
    private string name; 
    private string accountNo; 
    private string streetAddr1; 
    private string streetAddr2; 
    private string streetSuburb; 
    private string streetCity; 
    private string postAddr1; 
    private string postAddr2; 
    private string postSuburb; 
    private string postState; 
    private string postPC; 
    private string accountType; 
    private string accountSubType; 
    private string areaRep; 
    private string status; 
    private string overview; 
    private string bpcsId; 
    private string modifiedBy; 
    private DateTime modifiedDate; 
    private IList<Contact> contacts; 

    [PrimaryKey] 
    public int ID { get { return this.iD; } set { this.iD = value; } } 
    [Property] 
    public string Name { get { return this.name; } set { this.name = value; } } 
    [Property] 
    public string AccountNo { get { return this.accountNo; } set { this.accountNo = value; } } 
    [Property] 
    public string StreetAddr1 { get { return this.streetAddr1; } set { this.streetAddr1 = value; } } 
    [Property] 
    public string StreetAddr2 { get { return this.streetAddr2; } set { this.streetAddr2 = value; } } 
    [Property] 
    public string StreetSuburb { get { return this.streetSuburb; } set { this.streetSuburb = value; } } 
    [Property] 
    public string StreetState { get { return this.streetCity; } set { this.streetCity = value; } } 
    [Property] 
    public string StreetPC { get { return this.streetCity; } set { this.streetCity = value; } } 
    [Property] 
    public string PostAddr1 { get { return this.postAddr1; } set { this.postAddr1 = value; } } 
    [Property] 
    public string PostAddr2 { get { return this.postAddr2; } set { this.postAddr2 = value; } } 
    [Property] 
    public string PostSuburb { get { return this.postSuburb; } set { this.postSuburb = value; } } 
    [Property] 
    public string PostState { get { return this.postState; } set { this.postState = value; } } 
    [Property] 
    public string PostPC { get { return this.postPC; } set { this.postPC = value; } } 
    [Property] 
    public string AccountType { get { return this.accountType; } set { this.accountType = value; } } 
    [Property] 
    public string AccountSubType { get { return this.accountSubType; } set { this.accountSubType = value; } } 
    [Property] 
    public string AreaRep { get { return this.areaRep; } set { this.areaRep = value; } } 
    [Property] 
    public string Status { get { return this.status; } set { this.status = value; } } 
    [Property] 
    public string Overview { get { return this.overview; } set { this.overview = value; } } 
    [Property] 
    public string BPCSId { get { return this.bpcsId; } set { this.bpcsId = value; } } 
    [Property] 
    public string ModifiedBy { get { return this.modifiedBy; } set { this.modifiedBy = value; } } 
    [Property] 
    public DateTime ModifiedDate { get { return this.modifiedDate; } set { this.modifiedDate = value; } } 

    // Inverse ensures is read-only ie. Contact controls the relationship 
    // Castle will usually infer relationship, but we explicitly set just to be on the safe side 
    [HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId")] 
    [ScriptIgnore] 
    public IList<Contact> Contacts { get { return this.contacts; } set { this.contacts = value; } } 

    protected Company() { } 

    public Company(string Name, string StreetAddr1) 
    { 
     this.Name = Name; 
     this.StreetAddr1 = StreetAddr1; 

     ModifiedBy = "Test"; 
     ModifiedDate = DateTime.Now; 
    } 

    public static Company[] FindCompanies(string name) 
    { 
     return FindAll(Expression.InsensitiveLike("Name", "%" + name + "%")); 
    } 
} 

Répondre

3

se trouve que j'avais oublié le boîtier de chameau pour la propriété dataType sur ma demande ajax

Vieux:

$.ajax 
    ({ 
     type: "POST", 
     url: "Home.aspx/GetCompanies", 
     contentType: "application/json; charset=utf-8", 
     datatype: "json", 
     data: "{name: '" + strCompanySearch + "'} ", 
     success: companySearchSuccess, 
     error: onError 
    }); 

Solution

$.ajax 
    ({ 
     type: "POST", 
     url: "Home.aspx/GetCompanies", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     data: "{name: '" + strCompanySearch + "'} ", 
     success: companySearchSuccess, 
     error: onError 
    }); 

Hope this helps autres à éviter les heures de recherche google, des tutoriels et des blogs que j'ai souffert ... Doh!

+0

Heh, je viens de passer 30 minutes à m'arracher les cheveux en essayant de comprendre pourquoi mon script ne pouvait pas lire mon objet ... et c'était exactement cette erreur! : Bloomin 'cas langues sensibles. – Nick

1

Les WebMethods de Microsoft codent les données de retour à l'intérieur d'un objet nommé 'd'. Donc, vous devez changer votre code pour ressembler à ceci:

function companySearchSuccess(response) 
{ 
    // Get encoded data 
    response = response.d; // you could rename this, or just change the variable reference 

} 

Ceci est fait pour éviter un type particulier de javascript exploit. Vous pouvez voir plus de détails here et here.

+0

Ah, le redouté "d". Une "fonctionnalité" de sécurité très douteuse si vous me demandez ... de toute façon, "response = response.d || response;" serait plus approprié, comme les versions antérieures d'ASP.NET n'utilisent pas le wrapper "d". –

+0

Malheureusement j'utilise framework 2.0, donc ce n'est pas la solution. J'ai vérifié la réponse avec Firebug et la chaîne n'est pas enveloppée dans un objet "d" ... – mwjackson

+0

@Tsvetomir: bon ajout. Mais oui, cette 'fonctionnalité' rend les méthodes Web très incompatibles avec d'autres frameworks, ce qui peut être très pénible. – Travis

Questions connexes