Search code examples
c#ajaxrequestwebmethod

Ajax call to WebMethod failed


So I'm trying to do AJAX request to WebMethod (ASP .NET C#). I have looked at many topics for a solution to my problem but I cannot find anything.

Here is my current code:

<script type="text/javascript">

        function mostrarMensaje() {
            $.ajax({
                type: "POST",
                url: "index.aspx/devolverMensaje",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: 
                    function (msg) {
                        alert('El mensaje devuelto por el servidor es: ' + msg);
                    },
                error:
                    function (msg) {
                        alert(msg.status + " " + msg.statusText);
                    }
            });
        }
</script>

And that is my WebMethod:

namespace Test
{
    public partial class Formulario_web1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static String devolverMensaje() {
            return "pepe";
        }
    }
}

The response status is 0. Anyone can help me please? Thanks in advance!


Solution

  • The problem is already solved. The fault was mine that I had not seen that button just refresh the page before displaying the message.

    Thanks for atention!