2012-02-19 57 views
3

我使用此代碼訪問我的服務器(MVC),這工作正常。在結果「數據」({「Id」:30,「說明」:「樣品照片」,「名稱」:「第一Galery」})我嘗試獲取屬性data.Name,這只是沒有返回,什麼是在這個代碼中的問題?Json的結果是沒有什麼

的JavaScript

$(function() { 
     $('#UserGaleries_').change(function() { 
      try { 

       if ($(this).val() == -1) { 

        $('#NameGaleriesEdit').val(''); 
        $('#DescriptionGaleriesEdit').val(''); 

       } 
       else { 
        $.post('/UserGaleries/ChangeCategorie', 
         { selectedID: $(this).val() }, 
         function (data) { 
          alert(data.Name); //Nothing 
          $('#NameGaleriesEdit').val(data.name); 
          $('#DescriptionGaleriesEdit').val('asdf'); 

         }); 
       } 
      } catch (e) { 
       alert(e); 
      } 

     }); 
    }); 

MVC

[Serializable] 
public class ResponsetModel 
{ 
    public int Id { get; set; } 
    public string Description { get; set; } 
    public string Name { get; set; } 
} 

public JsonResult ChangeCategorie(int selectedID) 
{ 
    DbLayer.UserGaleriesManager uc = new DbLayer.UserGaleriesManager(); 
    DbLayer.Models.UsersGalery cat = uc.GetGaleriesById(selectedID); 

    ResponsetModel retValue = new ResponsetModel() 
    { Id = cat.Id, Name = cat.Title, Description = cat.Description }; 

    JsonResult oView = Json(retValue, "text/plain", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet); 
    return oView; 
} 
+0

您的ChangeCategories操作方法需要HttpPost屬性 – Jon 2012-02-19 20:36:33

+1

@Jon。這是不正確的。 – gdoron 2012-02-19 20:39:12

+0

不知道JavaScript的奧祕,但你有沒有嘗試調用data().name而不是? – 2012-02-19 20:39:36

回答

3

當您使用post()方法而不指定預期的內容類型,data將簡單地包含JSON(相對於JavaScript對象)的字符串。做alert(data)來驗證。

重寫後的

$.ajax({ 
    url:'/UserGaleries/ChangeCategorie', 
    data:{ selectedID: $(this).val() }, 
    method:"POST", 
    dataType:"json", 
    success:function (data) { 
     alert(data.Name); 
    } 
}); 

或者您可以使用$.getJSON(),但我不知道,如果你可以把它執行POST請求。

+0

謝謝,這個工作很好。 – AFetter 2012-02-19 20:54:58

2

您可以嘗試將$ .post()中的dataType設置爲「json」。檢查[文檔]中的示例。 1

它也是data.Name而不是data.name

事情是這樣的:

$.post('/UserGaleries/ChangeCategorie', 
              { selectedID: $(this).val() }, 
              function (data) { 
                            alert(data.Name); 
                            $('#NameGaleriesEdit').val(data.Name); 
                            $('#DescriptionGaleriesEdit').val('asdf'); 

              }, "json"); 

重要的建議:使用Firebug檢查什麼,從你的應用程序服務器的確切回覆。

-1

嘗試使用不同的方式訪問數據。使用數據[「姓名」]

+1

我不認爲這會有什麼區別.... data [「Name」]和data.Name應該是相同的,如果dataType是json。 – 2012-02-19 21:10:00

1

您還可以在使用JSON.parse(result)返回JSON數據後解析JSON數據。