从JavaScript调用C#方法并返回JSON

时间:2016-01-29 19:39:21

标签: javascript c# json webmethod

我正在努力使JavaScript与C#一起工作。现在,我只是想从C#中检索(GET)返回结果并通过JavaScript显示它。稍后,它将用于数据库写入(POST)。就像这样,在阅读之后,在这里我被卡住了:

我有按钮:

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

然后是JS代码:

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();
}

然后是C#WebMethod:

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

那么,我怎样才能获得&#34; WebMethod&#34;值&#34; onreadystatechange&#34;?并制作所有数据JSON?不需要为我编码,只是指出我正确的方向,就像我在这个概念上失败一样,因为我在正确的方式上阅读了许多相互矛盾的观点。没有jQuery。

2 个答案:

答案 0 :(得分:0)

要从java脚本调用C#方法,您必须使用ajax。以下是如何从java脚本或jquery调用c#方法的示例。

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

答案 1 :(得分:-1)

这可以为您提供与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; }
    }
}