Search code examples
c#asp.net-corerazor-pages

Why is the parameter value in Razor Pages named page handler null?


I'm using Razor Pages in an ASP.NET Core web application (.NET 7). In a Razor Page, I added a named page handler next to the default OnGetAsync handler.

public async Task<IActionResult> OnGetGetStatesAsync(string country)
{
    ...
}

This method is called from a JavaScript function.

$('.js-select-country').change(function (e) {
    
    var url = "MyPage?handler=getStates&country=US";
    
    $.getJSON(url, function (data) {
        ...
    });

The page handler is being called but the country parameter is null. I've played around with escaping the ampersand in the query string like & and %26 but that's also didn't fix it for me. Either the parameter is still null or the default OnGetAsync method is being called (with %26 in the url). It's also tried a route rather than a query string (getStates/US) and marking the C# parameter with FromRoute, but then also the wrong method is being called.

What should I change so that the parameter value is correctly set?


Solution

  • Pretty sure that the url should be written like the following code:

    var url = '?handler=GetStates&country=US',
    

    But I have to admit it is confusing that the first querystring parameter starts with & instead of ? which it is normally. I have also seen where a forward slash is used in the beginning like:

    '/?handler=GetStates&country=US'
    

    Perhaps then the handler is the first querystring parameter..

    Another Razor Page handler way I have seen:

    url: "@Url.Page("/MyPage")?handler=GetStates&country=US",