You are working with a "named handler". You pass in the name of the handler without the onpost or onget prefix or the async suffix, and you either pass that as a query string value named "handler" or you add an optional route parameter to your page named
"{handler?}"
Member
38 Points
217 Posts
How to call a c# method from javascript inside a razor page?
Feb 17, 2021 02:42 PM|igorbaldacci|LINK
Hi all,
I'm using a DateTimePicker inside my razor page, and I want to call a c# async method on the "changeDate" event of it.
This is my javascript, I'm trying to use jQuery:
This is my .cs code:
It doesn't work.
Some one could help me, please?
I repeat that I'm in a razor page, not in Blazor component.
All-Star
58134 Points
15641 Posts
Re: How to call a c# method from javascript inside a razor page?
Feb 17, 2021 04:00 PM|bruce (sqlwork.com)|LINK
The function needs to be a razor page handlers. Handlers name must begin with On<verb> in you case OnPost, so the function is
The in Ajax you pass the url <page name>/myfunction
Member
38 Points
217 Posts
Re: How to call a c# method from javascript inside a razor page?
Feb 17, 2021 05:17 PM|igorbaldacci|LINK
Thanks bruce,
I have tried this, but it doesn't work:
Any idea?
All-Star
194428 Points
28074 Posts
Moderator
Re: How to call a c# method from javascript inside a razor page?
Feb 17, 2021 06:00 PM|Mikesdotnetting|LINK
You are working with a "named handler". You pass in the name of the handler without the onpost or onget prefix or the async suffix, and you either pass that as a query string value named "handler" or you add an optional route parameter to your page named "{handler?}"
Read all about it: https://www.learnrazorpages.com/razor-pages/handler-methods
All-Star
58134 Points
15641 Posts
Re: How to call a c# method from javascript inside a razor page?
Feb 18, 2021 12:35 AM|bruce (sqlwork.com)|LINK
on reflection I find this just poor design (add Ajax handlers to a razor page). You should create a webapi controller for your Ajax calls.
Member
38 Points
217 Posts
Re: How to call a c# method from javascript inside a razor page?
Feb 18, 2021 07:47 AM|igorbaldacci|LINK
Thank you Mikesdotnett, especially for your link, it clarify me a lot of things.
Your suggestion works, the only change I made was the use of GET instead of POST.
Member
38 Points
217 Posts
Re: How to call a c# method from javascript inside a razor page?
Feb 18, 2021 07:50 AM|igorbaldacci|LINK
Bruce maybe you are right.
To simplify: I use a webapi to load data in my razor page, but I call it directly by "myFunction" method in c# code, and not in an Ajax call
I think I have more changes to manipulate datas and variables that I need in the page. But this is only my opinion. I'm new in use of razor page.
Thanks for your time.
Igor.