skip to Main Content

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


  1. 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:

    1. Making sure the $.ajax actually gets called. So if you have surrounding logic make sure it hits it as expected
    2. ajax has an error callback that you can add to the ajax call to see if there is an error. This has an example how to use an error callback to see what is wrong
    Login or Signup to reply.
  2. Place your <script> tags inside @section in the view and put @RenderSection at the bottom of _Layout.cshtml.

    // in your view
    @section Scripts {
        <script>
        // your script here
        ....
        </script>
    }
    

    Then put this is at the bottom of _Layout.cshtml and make sure it comes after jQuery:

    @RenderSection("Scripts", required: false)
    

    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").

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search