Return JSON with ASP.NET/C#

Asked

Viewed 1,897 times

3

I have the following codes

Default.aspx

<script type="text/javascript">
        /* Relógio */
        function startTime() {
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/GetNetworkTime',
                data: "{}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (dados) {
                    var m;
                    var s;
                    if (dados.minuto < 10) {
                        m = "0" + dados.minuto;
                    } else {
                        m = dados.minuto;
                    }
                    if (dados.segundo < 10) {
                        s = "0" + dados.segundo;
                    } else {
                        s = dados.segundo;
                    }
                    document.getElementById('txt').innerHTML = dados.hora + ":" + m + ":" + s;
                }
            });
            t = setTimeout('startTime()', 500);
        };
    </script>

Default.aspx.Cs

using System.Web.Services;

namespace LPGPontoKH
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GetNetworkTime()
        {
            DateTime datetime = DateTime.Now;

            var resultado = new
            {
                hora = datetime.Hour,
                minuto = datetime.Minute,
                segundo = datetime.Second
            };
            //O JavaScriptSerializer vai fazer o web service retornar JSON
            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Serialize(resultado);
        }

    }
}

My startTime javascript function is executed, but the Getnetworktime method is not called. Does anyone know what’s missing?

Log Error Generated.

{"Message":"Failure to authenticate." ,"Stacktrace":null,"Exceptiontype":"System.Invalidoperationexception"}

  • I think you are mixing MVC with Web Forms. I don’t know if this form will work.

  • I know very little about Web Forms @Gypsy

1 answer

4


To make this ajax call work in your Webforms application, you will need to change the route setting.

In the "~/App_start/Routeconfig.Cs" file, change from:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

After making this change and running the application again, you will see that Webmethod Getnetworktime() will run in the code Behind of the page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.