Solved

MVC 4 JsonResult Not Firing?

Posted on 2014-01-06
8
320 Views
Last Modified: 2014-01-11
I have JsonResult all-figured-out using MVC 3.
Now I'm having trouble using MVC 4.
I cannot get a result from my Admin controler, GetUsers action.

Q. Could using JQuery ver 2.0.3 be a problem? (I used ver 1.9.1 in MVC3)

[RouteConfig]
Note: I discovered in MVC3 this is needed to 'fire' the action for debugging purposes.

 public static void RegisterRoutes(RouteCollection routes)
 {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Admin1",
                url: "Admin/GetUsers/{id}",
                defaults: new { controller = "Admin", action = "GetUsers", id = "" });

                routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
}

[Action]
 public class AdminController : Controller
 {
       public JsonResult GetUsers(int id) 
        {
            Array data = myGroups.GetUsersInGroup(id);

            return Json(data, JsonRequestBehavior.AllowGet);
        }
 }

[View]
<script src="~/Scripts/jquery-2.0.3.min.js"></script>
<script type="text/javascript">

    $(document).ready(function () 
    {
        $(document).on("change", '#lbxGroups', function () 
        {
            alert(this.value); //Works!
        
           $("#lbxUsers").empty(); //Works!

            var params = {};
            params.id = this.value;

            $.getJSON("/Admin/GetUsers", $.param(params, true), function (data) {

                  $(data).each(function ()
                  {
                      $("#lbxUsers").append($('<option/>', { value: this.UserId }).html(this.UserName));
                  });
             });
        });
    });

</script>

Open in new window

0
Comment
Question by:WorknHardr
  • 4
  • 3
8 Comments
 
LVL 21

Accepted Solution

by:
Craig Wagner earned 500 total points
ID: 39760774
I'm not sure why you have that first route in there, it doesn't do anything different than the default route. I'm assuming you've already confirmed that the action method is never being called? I'd try removing that first route, from what I can see it's not necessary anyway.
0
 

Author Comment

by:WorknHardr
ID: 39761226
I originally used groupId instead of id...

Besides the obvious, do you think the Jquery version can cause issues?
0
 
LVL 4

Expert Comment

by:ItWorked
ID: 39761235
You need to provide exact problem first.
Which can be answered by following,

1) does your script is working fine?
2) Do ajax request is going to server?
3) Are you able to identify whether your GetUsers method is called?
4) At what level you are trying to access URL from $.getJSON("/Admin/GetUsers".. which is dependent on your current level...say you are at (http://something.com/hereYouare)

Please provide exact information so that one can point out.

After looking at your code, Your MVC code in controller and $.get seems right...

why you have onChange on document?
0
 

Author Comment

by:WorknHardr
ID: 39762362
Solution: I created a new controller named 'Manager' and cut-n-paste exact code from the non-working 'Admin' controller, did same for View. The new 'Manager & View works!

As a test, I deleted the non-working 'Admin' controller and view, cleaned & rebuild solution, closed & reopened VS2012, then created a new 'Admin' controller and view, it's NOT working either, just as before.

Problem: I don't why JQuery fails to find a url starting with '/Admin/'
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 4

Expert Comment

by:ItWorked
ID: 39764180
@WorknHardr,

I was expecting answer in line to my questions so that I can start from specific point...

such as 1) if script is not working then "Have you seen your scripts are loaded well? (not having any 404 error"

2) Does your break point hits when you call your ajax function?

do answer such question these will be too helpful.
0
 

Author Comment

by:WorknHardr
ID: 39764286
The new 'Manager' controller & view use identical code and scripts as before in the 'Admin' controller & view.

1. This time no 404 error!
2. Break Point now 'hit' correctly!
0
 
LVL 4

Expert Comment

by:ItWorked
ID: 39764334
what's the result at line
return Json(data, JsonRequestBehavior.AllowGet);

Open in new window


Also are you getting any error at controller?

if no then  try with following code..
 $.getJSON("/Admin/GetUsers", $.param(params, true), function (data) {

                  $(data).each(function ()
                  {
                      $("#lbxUsers").append($('<option/>', { value: this.UserId }).html(this.UserName));
                  });
             }).complete(function(result){
alert(result);

});

Open in new window


what results comes up?
0
 

Author Closing Comment

by:WorknHardr
ID: 39773694
thanks for helping me troubleshoot this weird problem...
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now