skip to Main Content

I am working on a product catalog in MVC and I need to return some JSON values from controller to the Index page. It starts with an AJAX call to a controller action in the following format:

        $('.GetData_Action').click(function (index) {
            RememberVerticalScroll();

            $.ajax({
                url: this.href,
                type: 'GET',
                success: function (result) {
                    //categoryID = result.categoryId;
                    //ShowProducts();
                }
            });
        });

this.href references the original ActionLink that was clicked. this.href is the controller/action that needs to be called and includes parameters int categoryID, int level. The ActionLink (which is in Index.cshtml too) looks as follows:

@Html.ActionLink(@item.CategoryName, "GetData", "SimpleMenu", new { categoryID = item.Id, level = level }, 
new { @class = "GetData_Action" })
       

After clicking this ActionLink with class GetData_Action the jquery function $(‘.GetData_Action’).click is called and the AJAX GET request is executed.

Now the controller Action that is called should return two JSON values to the success branch of the AJAX call and looks as follows:

        [HttpGet]
        public JsonResult GetData(int categoryID, int level)
        {
            string VerticalScrollPosition;
            if (Session["VertScrollPos"] != null)
            {
                VerticalScrollPosition = Session["VertScrollPos"].ToString();
                Session["VertScrollPos"] = null; // reset Session
            }
            else
            {
                VerticalScrollPosition = null;
            }
            return Json(new { categoryId = categoryID , VerticalScroll = VerticalScrollPosition }, JsonRequestBehavior.AllowGet);
        }

The problem is the following. When I click the ActionLink, the controller method is called and the method returns the JSON correctly, but then the browser redirects to a separate page with plain JSON data (see picture below). Instead, the controller should return the JSON to the success branch of the AJAX call, because I want to be able to use the result. I tried numerous different formats for the AJAX call, but neither of them changes the result. Also, executing and receiving a POST call instead of GET is not accepted by MVC and leads to a fault page saying that the controller was not found: a public action method was not found on controller.

The plain JSON page that is redirected to:

2

Answers


  1. Please remove the action link and pass parameters in the same ajax call, try modifying your ajax call as follows.

            $.ajax({
                url: '@Url.Action("UpdatePage", "Setup")',
                type: 'POST',
                data: {
                    'ID': PageId,
                    'PageName': $("#txtPageName").val(),
                    'DESCRIPTION': $("#txtDESCRIPTION").val(),
                },
                dataType: 'json',
                success: function (data) {
                    if (data.ErrorCode == "999") {
                        //toastr.error(data.Users);
                        clearFields();
                        //location.reload(true);
                    }
                    else {
                        //toastr.success(data.Users);
                        clearFields();
                        location.reload(true);
                    }
                },
                error: function (request, error) {
                    //GetUserData();
                    toastr.danger(request.Users);
                    //alert("Request: " + JSON.stringify(request));
                }
            });

    Also remove [HTTPGet] filter from action and decorate it with [HTTPPost] filter.

    Login or Signup to reply.
  2. because you triggering the click on action Link and the normal behavior when you click on a link is to redirect you to href behind it.
    you can fix it by calling preventDefault function inside your click event method as follow

     $('.GetData_Action').click(function (index) {
    
          index.preventDefault();
          RememberVerticalScroll();
    
                $.ajax({
                    url: this.href,
                    type: 'GET',
                    success: function (result) {
                        //categoryID = result.categoryId;
                        //ShowProducts();
                    }
                });
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search