我认为Form.cshtml中有这个ajax调用
<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>
}
以及我后面的Razor Pages代码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);
}
}
问题在于它没有达到OnPost方法。如果我放入OnGet,它将在之前自动加载,然后单击“提交”按钮。
我尝试在Filter.cshtml.cs中创建另一个名为Filter.cshtml的Razor页面。然后在我的Form.cshtml中,我将网址更改为/Filter/
,它的确到达了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);
}
}
答案 0 :(得分:1)
单击表单中的提交按钮的默认行为是提交表单。目前,您的表单未指定method
,因此提交将默认为GET
方法。如果要通过AJAX POST
提交表单,而不是通常的行为,则需要做两件事:
OnGet
处理程序执行的原因)POST
方法:@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>
}
答案 1 :(得分:0)
$。get()使用HTTP GET 方法发出Ajax请求,而$ .post()使用HTTP POST 方法发出Ajax请求。
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Filter/OnGet",
success: function (result) {
}
});