I have an ASP.net MVC and I am trying to get a string from a c# function using Ajax I have tried using this solution but nothing seems to work.
This is my controller function:
public string Test()
{
string test = "hi";
return test;
}
This is my script tag:
<script>
var textbox = document.getElementById("textbox");
textbox.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
$.ajax({
type: 'GET',
url: '@Url.Action("Test", "Home")',
success: function (result) {
alert("hi");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
});
</script>
2
Answers
I don’t think there is enough information presented to give an accurate solution. I created a local MVC application and added a Test() action method that returns a string and I was able to get the result with your ajax code.
A couple things you could try is:
Place your
<script>
tags inside@section
in the view and put@RenderSection
at the bottom of_Layout.cshtml
.Then put this is at the bottom of
_Layout.cshtml
and make sure it comes after jQuery:Explanation
My guess is jQuery is not loaded when the the DOM parses your javascript. If this is the case the your
$.ajax
call will never work.The current Visual Studio MVC templates (for .Net-core) place jQuery at the bottom of
_Layout.cshtml
. If you place<script>
tags in the middle of your view, they will appear before jQuery is requested by the browser.Placing the
<script>
tags inside a@section Scripts { }
element means that the javascript will actually be added to_Layout.cshtml
in the location specified by@RenderSection("Scripts")
.