Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

MVC 4 JsonResult Not Firing?

Posted on 2014-01-06
8
Medium Priority
?
387 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 2000 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:Hiran Desai
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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
 
LVL 4

Expert Comment

by:Hiran Desai
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:Hiran Desai
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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
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…
Suggested Courses

926 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