-1

I am trying to make JavaScript work with C#. For now, i am just trying to retrieve (GET) a return result from the C# and display it via JavaScript. Later, it will be for database writing (POST). Like so, and after reading, here's where i got stuck:

I have the button:

<button id="btn" onclick="Create();">CREATE</button>

Then JS code:

function Create() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        alert(xhttp.response)
    }
  };
xhttp.open("GET", "default.aspx/Create", true);
xhttp.send();
}

Then the C# WebMethod:

[WebMethod]
public static string Create()
{
    return "WebMethod";
}

So, how can i get the "WebMethod" value on "onreadystatechange"? And make all data JSON? Don't need to code for me, just point me in the right direction, as where i'm failing on the concept, as i read many conflicting opinions on the correct way. No jQuery.

Mr Billy
  • 151
  • 1
  • 2
  • 13
  • Why are you returning false? – JonH Jan 29 '16 at 19:41
  • For postback prevention, but without that still not working. I deleted from question too. Thank you. – Mr Billy Jan 29 '16 at 19:44
  • 1
    What are you trying to do, just make an ajax call ? – JonH Jan 29 '16 at 19:46
  • Yes, i am trying to get the response from the C# method for now. In the future, i want to send/receive to/from JS/C# in JSON. – Mr Billy Jan 29 '16 at 19:47
  • And are you using jquery or strictly js? – JonH Jan 29 '16 at 19:47
  • first google result: http://stackoverflow.com/questions/4508409/ajax-method-call – Erki M. Jan 29 '16 at 19:48
  • I want to use strictly JS, as jQuery is "too easy" and i want to learn JS very well before using it. Should i go for some C# class and create a response? Please point me in the right way, i know i'm missing something here. Thank you. – Mr Billy Jan 29 '16 at 19:49
  • @ErkiM. Good call, but that one is on Web Forms, which someone shouldn't learn as their first server-side technology anymore. Mr. Billy would want to look at MVC/Web API. – krillgar Jan 29 '16 at 19:51
  • @krillgar I am not really new to C#. Only new to JavaScript. His solution involves jQuery, and i don't want it. Please stick to my question. Thank you! – Mr Billy Jan 29 '16 at 19:54

2 Answers2

0

To call C# method from java script you have to use ajax. The following is an example how to call c# method from java script or jquery.

http://www.c-sharpcorner.com/UploadFile/8911c4/how-to-call-C-Sharp-methodfunction-using-jquery-ajax/

Hasan Zubairi
  • 1,037
  • 4
  • 23
  • 57
  • I want it without jQuery. How can i retrieve, in JavaScript, the return value that came from the C# WebMethod? – Mr Billy Jan 29 '16 at 20:11
  • In C# method encode in json and return. The receiving var will be in json format. – Hasan Zubairi Jan 29 '16 at 21:23
  • It returns the whole document. I guess i need to return some http response. Strangely, i don't have System.Runtime.Serialization.Json namespace that would help me encode it. I don't want to install any packages. – Mr Billy Jan 29 '16 at 21:30
  • why you are returning 'return [WebMethod]' it should be 'return somestringvariable' – Hasan Zubairi Jan 29 '16 at 21:33
  • It's just a string, whatever the text inside it. I am returning a string. – Mr Billy Jan 29 '16 at 21:45
-1

This could give you a starting point in combination with jQuery:

/ * test.html * /

<script>
    function Create() {
        // create some data object here
        var data = {
            value1: 'string 1',
            value2: 'string 2',
            value3: 'string 3'
        };

        // post data to c# web service (web method)
        $.ajax({
            url: 'default.aspx/processData', // the path to the *.aspx-file has to correct here!
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ formData: data }),
            async: true,
            success: function (msg, status) {
                console.log(msg.d);
            },
            failure: function (data) {
                console.log(msg.d);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus + " : " + errorThrown);
            }
        });
        return false;
    }
</script>
<button onclick="Create();">Create</button>

/ * default.aspx * /

<%@ Page Language="C#" Src="default.aspx.cs" Inherits="main" %>

/ * default.aspx.cs * /

using System;
using System.Web.Services;
using System.Web.UI;

public class main : Page {
    protected void Page_Load(object sender, EventArgs e) { }

    [WebMethod]
    public static string processData(FormData formData) {
        //access your data object here e.g.:
        string val1 = formData.value1;
        string val2 = formData.value2;
        string val3 = formData.value3;

        return val1;
    }

    // the FormData Class here has to have the same properties as your JavaScript Object!
    public class FormData {
        public FormData() { }

        public string value1 { get; set; }
        public string value2 { get; set; }
        public string value3 { get; set; }
    }
}
Roland Krinner
  • 421
  • 2
  • 10