ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,662 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I just started learning ASP.NET Razor pages. Now I have a need to use AJAX/jQuery to get some data back from a model. I have the following code:
<script type="text/javascript">
function test() {
$.get('?handler=Echo&msg=hello',
function (data, status, xhr) {
$('#result').text(status + ':\n' + data)
}).fail(function (xhr, status, error) {
$('#result').text(status + ': ' + error + '\ntext:\n' + xhr.responseText)
}) }
</script>
public ActionResult<string> OnEcho(string msg) {
return Content(msg);
}
But it seems ActionResult does not work quite right; insead of getting the echoed back string, I get whole HTML source code instead. What should I do?
Working example
public class TestModel : PageModel
{
public void OnGet()
{
}
public JsonResult OnGetEcho(string msg)
{
return new JsonResult(msg);
}
}
@page
@model RazorPagesDemo.Pages.TestModel
<div>
<button type="button" id="echo">Echo</button>
</div>
<div>
<textarea id="result" name="result" rows="5" cols="50"></textarea>
</div>
@section scripts {
<script>
$('#echo').click(function () {
$.get('?handler=Echo&msg=hello',
function (data, status, xhr) {
$('#result').text(status + ':\n' + data)
}).fail(function (xhr, status, error) {
$('#result').text(status + ': ' + error + '\ntext:\n' + xhr.responseText)
})
});
</script>
}
https://www.mikesdotnetting.com/article/318/working-with-json-in-razor-pages