繁体   English   中英

在Asp.net C#中使用jQuery Ajax插入数据[数据库MySQL]

[英]Insert Data Using jQuery Ajax in Asp.net C# [Database MySQL]

我需要在Asp.net C#中使用jQuery Ajax在MySql数据库中插入新记录。

我在使用WebService方法时尝试了本教程: https : //codepedia.info/insert-data-using-jquery-ajax-in-asp-net-csharp-database-ms-sql-server/

我没有错误,但是没有插入数据。

我尝试插入简单的查询sql,但未成功。

你能帮助我吗?

先感谢您。

我的代码简化如下。

WebService.cs

using System;
using System.Configuration;
using System.Data.Odbc;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class WebService : System.Web.Services.WebService
{
    public WebService()
    {

    }

    public class userDetails
    {
        public string firstName;
    }

    [WebMethod]
    public void AddRecord(userDetails userDetails)
    {
        //SIMPLE SQL QUERY INSERT INTO
        string query = String.Format(" INSERT INTO doTable ");
        query += String.Format(" (name) ");
        query += String.Format(" VALUES ('foo'); ");

        using (OdbcConnection conn =
            new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
        {
            using (OdbcCommand cmd =
                new OdbcCommand(query, conn))
            {
                try
                {
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("operation failed!", ex);
                }
                finally
                {
                    cmd.Connection.Close();
                }
            }
        }
    }
}

HMTL页面:

<script src="3.2.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#activatedLink").on('click', function (e) {

            e.preventDefault();
            var userDetails = {};

            userDetails.firstName = $("#randomdirectory").val();

            var jsonData = JSON.stringify({
                userDetails: userDetails
            });

            $.ajax({
                type: "POST",
                url: "WebService.asmx/AddRecord",
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnErrorCall
            });

            function OnSuccess(response) {
                var result = response.d;
                if (result == "success") {
                    $("#msg").html("New record addded successfully  :)").css("color", "green");
                }
                $("#randomdirectory").val("");
            }

            function OnErrorCall(response) {
                $("#msg").html("Error occurs  :(").css("color", "red");
            }

        });

    });

</script>



<form id="form1">
    <div id="Tree">
       <input type="hidden" id="randomdirectory" name="randomdirectory" value="CEF">
          <a id="activatedLink" data-id="CEF" 
           href="javascript:document.getElementById('loading').style.visibility = 'visible';
           location.href='http://...';" target="_top">
          <span>CEF</span></a>
    </div>
</form>

在此处输入图片说明

您需要知道REST Service和SOAP Service .NET之间的区别。asmx Web服务是SOAP Service,这就是为什么带有字符串化json的普通ajax发布无法正常工作的原因。 SOAP请求spesifications写在您创建的页面中,例如https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit

例如,如果要请求该服务,则需要创建自己的身体,例如:

var data = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <CelsiusToFahrenheit xmlns="https://www.w3schools.com/xml/">
      <Celsius>{Your Value}</Celsius>
    </CelsiusToFahrenheit>
  </soap12:Body>
</soap12:Envelope>';

这应该是您的请求的主体,您需要设置请求标头的字段,例如:

 $.ajax({
                type: "POST",
                url: "https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit",
                data: data,
                contentType: "application/soap+xml; charset=utf-8",
                dataType: "text/xml",
                success: function(data) {
                    console.log('success'); 
                },
                error: function(data) {
                    console.log('failure');
                },
            });

之后,您可以发出成功的SOAP请求。

you can also create a static web method at back end of aspx page and can call back end method and insert data
use below code :

write web method at back end in aspx.cs file:
[WebMethod]

public static void AddRecord(userDetails userDetails)
{
    //SIMPLE SQL QUERY INSERT INTO
    string query = String.Format(" INSERT INTO doTable ");
    query += String.Format(" (name) ");
    query += String.Format(" VALUES ('foo'); ");

    using (OdbcConnection conn =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        using (OdbcCommand cmd =
            new OdbcCommand(query, conn))
        {
            try
            {
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new ApplicationException("operation failed!", ex);
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
    }
}




    <script src="3.2.1/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $("#activatedLink").on('click', function (e) {

                e.preventDefault();
                var userDetails = {};

                userDetails.firstName = $("#randomdirectory").val();

                var jsonData = JSON.stringify({
                    userDetails: userDetails
                });

                $.ajax({
                    type: "POST",
                    url: "pagename.aspx/AddRecord",     //here specify the name of our page where the method is present
                    data: jsonData,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    error: OnErrorCall
                });

                function OnSuccess(response) {
                    var result = response.d;
                    if (result == "success") {
                        $("#msg").html("New record addded successfully  :)").css("color", "green");
                    }
                    $("#randomdirectory").val("");
                }

                function OnErrorCall(response) {
                    $("#msg").html("Error occurs  :(").css("color", "red");
                }

            });

        });

    </script>



    <form id="form1">
        <div id="Tree">
           <input type="hidden" id="randomdirectory" name="randomdirectory" value="CEF">
              <a id="activatedLink" data-id="CEF" 
               href="javascript:document.getElementById('loading').style.visibility = 'visible';
               location.href='http://...';" target="_top">
              <span>CEF</span></a>
        </div>
    </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM