简体   繁体   中英

Calling Json from MVC View

I am not sure what I am doing wrong here.

I have a list where I am creating hyperlinks. I need to point the user to the right page first though so I do a getJson.

I have the following code in my .cshtm file:

            $.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");                    
             }
           });

I have the following code in the controller:

    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);
    }

The problem I am facing is that the Json method never gets called.

Your controller method is declared as private - As such it would not be accessible.

Change it to public .

Secondly, you should activate allow get - Details on why this is not set by default see - Why is JsonRequestBehavior needed?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM