0
votes

I have a razor page model. In this model there is a get-Method.

public IActionResult OnGetDuration([FromBody]int id)
    {
        Subject subject = _service.GetSubjectById(id);
        int duration = subject.LessonsPerWeek;
        return new JsonResult('a');
    }

I call this method with Ajax in JavaScript:

function getHours(i, studentId) {
var selection = document.getElementById('select_' + i);
var id = parseInt(selection.options[selection.selectedIndex].value);
var json = JSON.stringify(id);
$.ajax({
    type: 'GET',
    contentType: 'application/json',
    data: json,
    dataType: 'json',
    url: "/Subjects/Choose?handler=Duration",
    cache: false,
    success: function (result) {
        alert(result);
    },
    error: alert('error calling my ajax request')
    });
}

This leads to an error:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
  An unhandled exception has occurred while executing the request.

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken) at

Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterConte xt context, Encoding encoding) at

Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterConte xt context, Encoding encoding) at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext) at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value) at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageBinderFactory.<>c__DisplayClass3_0. <g__Bind|0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.BindArgumentsCoreAsync() at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

This error seems to be caused when receiving the json on server side.

An ID for example 81 is given to the ajax call. But I am receiving the parameter id = 0 on C#.

If I send the id as string the parameter received on C# is null.

This id leads to a Nullreference Excption in the GET C# method.

How can I solve this error ?

1
The console output (Error) is: Failed to load resource: the server responded with a status of 500 ()eisem
I cant find the request body in the developer tools of Microsoft Edge.eisem
I cannot see a request body there but a request header.eisem
This is the request header:eisem
:authority: localhost:5001 :method: GET :path: /Subjects/Choose?handler=Duration&81&_=1605273709748 :scheme: https accept: application/json, text/javascript, /; q=0.01 accept-encoding: gzip, deflate, br accept-language: de,de-DE;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6 cache-control: no-cache content-type: application/json pragma: no-cache referer: localhost:5001/Subjects/Choose?id=10 sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: same-origineisem

1 Answers

0
votes

Sorry, for me it is not clear what you are trying to do. Your method says [FromBody], however I can't see the body in your ajax request.

By chance is the Duration the value You want to receive on the ID parameter?
url: "/Subjects/Choose?handler=Duration".

If so, then You are trying to pass the value as query string. Change your method to

([FromQuery]int id)

and your url call to

url: "/Subjects/Choose?id=Duration"

Or another approache, change your route to

@page "*here the current route*/{id}"

and your method to

([FromRoute]int id)