Home > database >  How to send Data from aspx page using Ajax on userclick to C# page?
How to send Data from aspx page using Ajax on userclick to C# page?

Time:10-08

I am working with .Net Framework 4.6.1 I have a aspx page that renders data using a Telerik controller. I need to be able to pass properties from the Telerik controller back to the C# page. I have it set up so that when the user clicks on a row column it runs the ajax method with a hardcoded value. I'm unable to send my value using Ajax, I get sent to the error response right away. Is there something I'm doing wrong? I'm searched everywhere for documentation but none of it works with my framework... aspx.cs page aspx page

ASPX Page

<telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="False" AllowSorting="False" AllowFilteringByColumn="False" OnNeedDataSource="GetPharmacyByCorporate">
    <ClientSettings>
        <Scrolling AllowScroll="True" ScrollHeight="650px" UseStaticHeaders="True"></Scrolling>
        <ClientEvents OnRowClick="sendIndex" />
        <%-- On user click (client side) --%>
    </ClientSettings>
    <MasterTableView>
        <Columns>
        </Columns>
        <%-- Columns renders every item passed --%>
    </MasterTableView>
</telerik:RadGrid>
<script>
    function sendIndex() {
        $.ajax({
            url: "/CorpPharmacyList/getIndexed",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: { "indexValue": "4" },
            success: function (data) {
                if (data) {
                    console.log("Post successful");
                }
            },
            error: function (e) {
                console.log("There was an error with the ajax call")
            }
        })
    }
</script>

C# Page

public class indexed
    {
        public int indexValue { get; set; }
    }

    [WebMethod]
    public void getIndexed(indexed indexe)
    {
        try {
            var myVar = indexe.indexValue;
        }
        catch (Exception ex)
        {

        }
    }

CodePudding user response:

Based on a comment on the question above...

This is the error I'm gettng "Unexpected token '<', " <!DOCTYPE "... is not valid JSON"

That means the server isn't returning JSON, it's returning HTML. But the JavaScript code is explicitly expecting JSON:

dataType: 'json',

Looking at the server-side code, this makes sense. Because the server-side code doesn't return anything:

public void getIndexed(indexed indexe)

So it would appear that it is defaulting to a page of some kind.

You can tell the JavaScript code to expect HTML instead:

dataType: 'html',

If you modify the server-side code to return JSON data, just remember to change it back on the client.

  • Related