Unable to call handler in Razor page from JQuery

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

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.
2,536 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.
6,934 questions
{count} votes

5 answers

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

    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)

    No comments

  2. answered 2023-01-24T16:08:58.23+00:00
    Karen Payne MVP 29,236 Reputation points Microsoft MVP

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

  3. answered 2023-01-24T16:09:25.23+00:00
    AgaveJoe 17,021 Reputation points

    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. answered 2023-01-24T17:07:44.57+00:00
    TheCoder 91 Reputation points

    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. answered 2023-01-24T19:31:12.63+00:00
    AgaveJoe 17,021 Reputation points

    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.

    No comments