2012-08-24 68 views
1

我第一次尝试我的手在Json,我不确定我在这里做错了什么,但我的成功回调被调用。我有一个名为RIPreset的下拉菜单,它在更改时调用下面的代码。我知道更换部分工作正常。在我的alert(“popup1”)代码运行的代码中,我的代码中还有一个断点,并且可以看到getPreset方法正在调用并将字符串传递给结果,但在我的函数内部没有任何内容。 getJSON调用。即,alert(“popup2”)永远不会被调用。我认为这意味着我没有从我的JsonResult传递有效的数据,但我不确定我做错了什么。任何帮助,将不胜感激。如何获得.getJson成功

代码隐藏

public JsonResult getPreset(int id) 
    { 
     RIPreset ripreset = db.RIPresets.Find(id); 
     return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount }); 

    } 

的JQuery/Json的

<script type="text/javascript"> 
$(document).ready(function() { 
    $("#RIPreset").change(function() { 

     var selection = $("#RIPreset").val(); 
     alert("popup1"); 
     $.getJSON('@Url.Action("getPreset")', { id: selection }, function (ripreset) { 
      alert("popup2"); 
      $("#txtDescription").val(ripreset.Description); 
      $("#txtHourlyRate").val(ripreset.HourlyRate); 
      $("#txtLaborHours").val(ripreset.LaborHours); 
      $("#txtAmount").val(ripreset.Amount); 
     }); 
    }); 
}); 
</script> 
+0

不知道这有多相关,但如果您在调试ajax请求时遇到问题,我建议您在浏览器中使用开发控制台进行调试 - 例如萤火虫或chrome开发工具 –

回答

2

GET请求都被禁止在默认情况下出于安全原因,改变你的行动返回

public JsonResult getPreset(int id) 
    { 
     RIPreset ripreset = db.RIPresets.Find(id); 
     return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount }, 
        JsonRequestBehavior.AllowGet); 

    } 
+0

这个伎俩!谢谢一堆。只是一个附注,如果你不想使用它,为什么你会传递一个JSON对象? –

+0

请参阅答案[这里](http://stackoverflow.com/questions/8464677/why-is-jsonrequestbehavior-需要) – StanK

1

只是改变你的操作是这样的:

 
public JsonResult getPreset(int id) 
{ 
    RIPreset ripreset = db.RIPresets.Find(id); 
    return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount }, JsonRequestBehavior.AllowGet); 
} 
+0

这样做。 –