Reputation: 369
I'm having trouble extracting data from an AJAX request in ASP.NET Core Razor Pages.
Ajax Request Code (contained in a <script>
block on a razor pages .cshtml page:
$("body").ready(function AjaxTest() {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'text',
url: '/Menus/Admin_MainMenu?action=TestMethod',
method: 'GET',
success: function (data) {
alert("Request Successful" + data);
},
error: function () {
alert("Request Failed");
}
});
})
And the corresponding PageModel method (just as test at the moment):
[HttpGet]
public string TestMethod()
{
string mystring = "success";
return mystring;
}
I know the request works, as I get the alert "Request Successful". However, instead of "Request Successful" being followed by my value of mystring
, I get a string of HTML corresponding to the layout of the .cshtml page.
I've tried changing the data type to JSON (both in the AJAX request using dataType
, and in the method return type (jsonrequest
), but that makes the request fail.
Any help is greatly appreciated. Thanks.
Upvotes: 0
Views: 4740
Reputation: 24957
The problem when using dataType: 'text'
is that the string may rendered as HTML output instead of simple string. Also declaring function AjaxTest()
inside ready
event is not a proper way to declare function inside AJAX callback, even the syntax is valid because of scoping issue.
You need to use JsonResult
return type instead of string
:
public JsonResult OnGetTestMethod()
{
string mystring = "success";
return new JsonResult(mystring);
}
Then use handler
parameter inside AJAX call:
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Menus/Admin_MainMenu?handler=TestMethod',
type: 'GET',
success: function (data) {
alert("Request Successful " + data);
},
error: function () {
alert("Request Failed");
}
});
});
Note:
1) The JsonResult
mentioned here is not System.Web.Mvc.JsonResult
, it uses Microsoft.AspNetCore.Mvc.JsonResult
and doesn't have JsonRequestBehavior
property.
2) Razor pages uses OnGet
and OnPost
action method prefixes to deal with HTTP GET and POST respectively, hence the [HttpGet]
attribute is unnecessary.
Further references:
Handle Ajax Requests in ASP.NET Core Razor Pages
ASP.NET Core Razor Pages: How to implement AJAX requests
Upvotes: 2