0
votes

I have this ajax call in my view, Form.cshtml

<form id="myForm">    
<input id="btnSubmit" type="submit" value="Load data" />
<p id="result"></p>
</form>
@section scripts{
<script type="text/javascript">
    $(function () {
        $('#btnSubmit').click(function () {
            debugger
            $.get('/Form/',function (data) {
            debugger
            console.log('test');                
        });
        })

    });
</script>
}

and in my Razor Pages code behind, Form.cshtml.cs

    public class FormModel : PageModel
{
    public JsonResult OnPost()
    {
        List<Student> students = new List<Student>{
            new Student { Id = 1, Name = "John"},
            new Student { Id = 2, Name = "Mike"}
        };

        return new JsonResult(students);
    }
}

The problem is it doesn't reach OnPost method. If I put in OnGet, it will automatically load before I click the Submit button.

I try to create another Razor page called Filter.cshtml and in Filter.cshtml.cs. And then in my Form.cshtml, I changed my url to /Filter/, it did reach OnGet in Filter.cshtml.cs

    public class FilterModel : PageModel
{

    public JsonResult OnGet()
    {
        List<Student> students = new List<Student>{
            new Student { Id = 1, Name = "John"},
            new Student { Id = 2, Name = "Mike"}
        };

        return new JsonResult(students);
    }
}
2
You should use the jQuery post method, not get: $.post('/Form/',function (data)... - Mike Brind
I tried with post but still didn't reach OnPost - Steve
@Steve check ive modified answer - Nijin P J

2 Answers

1
votes

The default behaviour of clicking a submit button in a form is that the form gets submitted. At the moment, your form has no method specified, so the submission will default to the GET method. If you want to submit the form by AJAX POST rather than the usual behaviour, you need to do two things:

  1. Cancel the default action of the button click (which is what currently causes the OnGet handler to execute)
  2. Change the jQuery code to use the POST method:
@section scripts{
<script type="text/javascript">
    $(function () {
        $('#btnSubmit').click(function (e) { // include the event parameter
            e.preventDefault(); // prevents the default submission of the form
            $.post('/Form/',function (data) { // change from 'get' to 'post'
                console.log('test');                
            });
        });
    });
</script>
}
0
votes

the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.

 $.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: "/Filter/OnGet",
  success: function (result) { 
   }
 });