0

Iam trying to send some JSON data to the server using jquery ajax call. It doesn't seem like the data is posting as when i try to parse it in the code-behind file it throws errors. Searched around but the answers didn't help solve my problem. Any guidance would be appreciated.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">

    $.ajax({
        url: 'Default2.aspx',
        type: 'post',
        async: false,
        contentType: 'application/json; charset=utf-8',
        //data: "'"+batchtable+"'",
        data: JSON.stringify({"a":"1", "b": "2"}),
        dataType: 'json',
        processData: false,
        success: function (result) {
            alert('success');
        },
        error: function (result) {
            alert('failed');
        }
    });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

And here is the .cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;
using System.Web.Script.Serialization;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        var jsonString = String.Empty;
        HttpContext context = HttpContext.Current;
        context.Request.InputStream.Position = 0;
        using (var inputStream = new StreamReader(context.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }

        RootObject userinput = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(jsonString);

    }
}

public class RootObject
{
    public string a { get; set; }
    public string b { get; set; }
}

The error message I get is:

Invalid JSON primitive: __VIEWSTATE.

2 Answers 2

2

for ajax call don't call from server side event.you need to call from javascript/jquery.

you need to define a serverside webmethod and you can call that method from the jquery/javascript. here is a demo. works fine. might be helpful for you.

 <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
 <script language="javascript" type="text/javascript">
     $(document).ready(function () {
         $("#btnResult").click(function () {
             var name = $("#txtNameTextBox").val();
             $.ajax({
                 type: "POST",
                 url: "Default.aspx/GetDate",
                 data: "{name:'" + name + "'}",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function (data) {
                     //alert(data.d);
                     $("#Result").text(data.d);

                     var val = data.d;
                     val = val.split("~");
                     var name = val[0];
                     var time = val[1];
                     var date = val[2];
                     var tempdate = date.split(":");
                     var finaldate = tempdate[1];
                     $("#txtDateToDisplay").val(finaldate);
                     $("#txtDateToDisplay2").val(finaldate);
                 },
                 error: function () { alert(arguments[2]); }
             });
         });

     });
 </script>

here is HTML

<h2>
    Call Server side Function From JaxaScript AJAX Call ASP.NET!
</h2>
<br />
<br />
<div>
  Name  : <input type="text" id="txtNameTextBox" /><br/><br/>
  Date  : <input type="text" id="txtDateToDisplay" /><br/><br/>
  Date  : <input type="text" id="txtDateToDisplay2" />
  <br />
  <br />
  <p id="Result">Message : </p>
 <input type="button" id="btnResult" value="Click here for the time"/>
</div>

And here your server side code

     /// <summary>
    /// ===========================================
    /// This is the WebMethod where ajax call happens.
    //=============================================
    /// </summary>
    /// <param name="name">the data sent from ajax call 
    /// - here a string only(name of a user)</param>
    /// <returns>a string with json format</returns>

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string GetDate(string name)
    {
        if (name == "")
        {
            return "No Parcel Available";
        }
        else
        {
            name = "Name : " + name + "~" +
                    "Current Time : " + DateTime.Now.ToLongTimeString()
                    + "~" + "Date : " + DateTime.Now.ToShortDateString();
        }

       return name;
    }

Hope it will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the response. The issue turned out to be totally unrelated (jquery library issues). My mistake for not verifying that first..
1

You need to use JavaScript/jQuery to call a server-side endpoint. ASP.NET AJAX Page Methods provide web methods that are hosted inside of a page, but are static and are not part of the page instance, so you can call them asynchronously via your client-side script, like this:

Markup:

<div id="Results"></div>

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "YourPage.aspx/GetGreeting",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            // Put greeting into DIV
            $('#Results').text(result.d);
        }
    });
});

Code-behind:

[WebMethod]
public static string GetGreeting()
{
    return "Hello world!";
}

Note: The above example uses the client (via jQuery) to ask the server for a greeting (string), which is JSON-encoded automatically by the ASP.NET AJAX Page Method. The result is then processed by the success handler of the jQuery .ajax() function and the actual string value is pulled out of the .d reference in the returned JSON object.

1 Comment

thanks for the response. The issue turned out to be totally unrelated (jquery library issues). My mistake for not verifying that first..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.