从MVC View调用Json

Nat*_*Pet 1 c# asp.net-mvc-3

我不确定我在这里做错了什么.

我有一个列表,我正在创建超链接.我需要先将用户指向正确的页面,所以我做了一个getJson.

我的.cshtm文件中有以下代码:

            $.getJSON('/Home/GetLocType', { "locId": loc.locId },  
              function(result) {   
                result = Json.stringify(result);                


             if(result == '1')                     
             {

                $('<li><a id=' + loc.locId + ' href="/DataEntry"  rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");

             }
             else
             {
                $('<li><a id=' + loc.locId + ' href="/DataEntry/PForm"  rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");                    
             }
           });
Run Code Online (Sandbox Code Playgroud)

我在控制器中有以下代码:

    private JsonResult GetLocType(int locId)
    {
        int locationId = Convert.ToInt32(locId);            
        var result = db.Locations.Where(a => a.LocID == locationId).Select(a => a.TypeId);
        return Json(result);
    }
Run Code Online (Sandbox Code Playgroud)

我面临的问题是Json方法永远不会被调用.

Kam*_*ami 6

您的控制器方法声明为private- 因此无法访问.

将其更改为public.

其次,你应该激活allow get - 默认情况下没有设置为什么的详细信息请参阅 - 为什么需要JsonRequestBehavior?

public JsonResult GetLocType(int locId)
{
    int locationId = Convert.ToInt32(locId);            
    var result = db.Locations.Where(a => a.LocID == locationId).Select(a => a.TypeId);
    return Json(result, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)