Unable to call handler in Razor page from JQuery

TheCoder 91 Reputation points
2023-01-24T14:29:16.1966667+00:00

I'm trying to call a handler in my Razor code behind to bind a table and it's not getting executing.

CS code:

public async Task<JsonResult> OnGetCarList()
{
      var cars = await _context.GetCars.ToListAsync();
      return new JsonResult(cars);
}

and the Jquery:

$().ready(function(){
     $.getJSON('/Index/?handler=GetCarList', function(data) {
           console.log(data) //there is no data
        }
    
}

when I set a breakpoint at the method, it never gets hit. Am I missing something?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,229 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,363 questions
{count} votes

5 answers

Sort by: Most helpful
  1. TheCoder 91 Reputation points
    2023-01-24T15:30:09.0733333+00:00

    Hello Karen, the interesting thing is, I'm able to databind two dropdowns doing the same thing with no issues, however, when trying to call the code behind handler on this page fails.

    [ this way is working for me to bind a drop down]

    I'm binding a drop down as:

    this will return me data, however, the same way in my OP will not. What's the difference? I'm using .NET CORE with Razor

    $.getJSON('/Index/?handler=GetCarTypes', { type: carType }, function(data) {
          //this will return data
    )};
    
    

    I was reading that post earlier and tried some of the examples, and they still failed for me. (no data returned)

    0 comments No comments

  2. Karen Payne MVP 35,196 Reputation points
    2023-01-24T16:08:58.23+00:00

    I cloned the repository and added code in $(document).ready(function ()

    E1

    See my version

    $(document).ready(function () {
    
        $.ajax({
            type: "GET",
            url: "@Url.Page("/Index")?handler=ContinentsNamesList",
            contentType: "application/json",
            dataType: "json",
            success: function (response) {
                var dvItems = $("#dvItems");
                dvItems.empty();
                $.each(response, function (i, item) {
                    var $tr = $('<li>').append(item).appendTo(dvItems);
                });
            },
            failure: function (response) {
                alert(response);
            }
        });
        
    });
    
    0 comments No comments

  3. AgaveJoe 26,161 Reputation points
    2023-01-24T16:09:25.23+00:00

    I've tried that as well and it doesn't get called from the JQuery on the view page

    Works perfectly on my end.

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <button id="ajax">OnGetCarList</button>
    </div>
    
    @section Scripts
        {
        <partial name="_ValidationScriptsPartial" />
        <script>
            $('#ajax').click(function () {
                console.log('click');
                $.getJSON('/Index/?handler=CarList', function (data) {
                    console.log(data);
                });
            });
        </script>
    }
    
    

    C#

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPagesBasicDemo.Pages
    {
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
    
            public IActionResult OnGet(string title)
            {
    
                return Page();
            }
    
            public JsonResult OnGetCarList()
            {
                ViewModel vm = new ViewModel() { Message = "Hello World" };
    
                return new JsonResult(vm);
            }
    
            public class ViewModel
            {
                public string Message { get; set; }
            }
        }
    
    }
    

    There must be something else wrong with your code base.


  4. TheCoder 91 Reputation points
    2023-01-24T17:07:44.57+00:00

    I got it working:

    changed this:

    url: "@Url.Page("/Index")?handler=ContinentsNamesList",
    
    

    to this: which is similar Karen's post, but I had to wrap [ /Index/ ] in quotes such as ("/Index/") and it worked.

    url: "@Url.Page("/Index/")?handler=CarList",
    
    

  5. AgaveJoe 26,161 Reputation points
    2023-01-24T19:31:12.63+00:00

    I think it is worth your time to learn URL paths and routes in ASP.NET Core. Your original URL path has two errors. First the path was looking for an Index razor page in the application root due to the beginning forward slash; /Index. Second, the handler was incorrectly named. The following might have worked depending on the your unknown folder structure. The path looks for the CarTypes folder in the application root.

     $.getJSON('/CarTypes/Index/?handler=CarList',
    

    The new code with the Url.Page renders the following HTML.

    $.getJSON("?handler=CarList",
    

    This format uses the URL currently displayed in the address bar.

    0 comments No comments