You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ASP.NET C#中用JavaScript插入数据库数据,插入后弹出alert提示框

在ASP.NET C#中通过JavaScript实现数据库插入并弹出成功提示

由于浏览器端JavaScript无法直接访问服务器数据库,必须通过后端C#接口完成数据插入操作,前端使用AJAX调用接口,根据返回结果弹出提示框。以下是具体实现步骤:

后端(C#)实现

1. WebForms:编写WebMethod

在你的ASPX页面后台代码(.aspx.cs)中添加静态WebMethod,用于接收前端参数并执行插入逻辑:

using System;
using System.Data.SqlClient;
using System.Web.Services;

public partial class InsertDataPage : System.Web.UI.Page
{
    // 建议将连接字符串配置在Web.config中,此处为示例
    private static string _connString = "Data Source=你的服务器地址;Initial Catalog=你的数据库名;User ID=用户名;Password=密码;";

    [WebMethod]
    public static bool InsertUserData(string userName, string userEmail)
    {
        try
        {
            // 使用using自动释放数据库连接资源
            using (SqlConnection conn = new SqlConnection(_connString))
            {
                string insertSql = "INSERT INTO Users (UserName, UserEmail) VALUES (@UserName, @UserEmail)";
                using (SqlCommand cmd = new SqlCommand(insertSql, conn))
                {
                    // 参数化查询防止SQL注入
                    cmd.Parameters.AddWithValue("@UserName", userName);
                    cmd.Parameters.AddWithValue("@UserEmail", userEmail);

                    conn.Open();
                    int affectedRows = cmd.ExecuteNonQuery();
                    // 影响行数>0表示插入成功
                    return affectedRows > 0;
                }
            }
        }
        catch (Exception ex)
        {
            // 此处可添加日志记录逻辑
            return false;
        }
    }
}

2. MVC:编写POST Action

如果是MVC项目,在控制器中添加处理插入的POST Action:

using System.Data.SqlClient;
using System.Web.Mvc;

public class UserController : Controller
{
    private string _connString = "Data Source=你的服务器地址;Initial Catalog=你的数据库名;User ID=用户名;Password=密码;";

    [HttpPost]
    public JsonResult InsertUser(string userName, string userEmail)
    {
        bool isSuccess = false;
        try
        {
            using (SqlConnection conn = new SqlConnection(_connString))
            {
                string insertSql = "INSERT INTO Users (UserName, UserEmail) VALUES (@UserName, @UserEmail)";
                using (SqlCommand cmd = new SqlCommand(insertSql, conn))
                {
                    cmd.Parameters.AddWithValue("@UserName", userName);
                    cmd.Parameters.AddWithValue("@UserEmail", userEmail);

                    conn.Open();
                    isSuccess = cmd.ExecuteNonQuery() > 0;
                }
            }
        }
        catch
        {
            isSuccess = false;
        }
        return Json(new { Success = isSuccess });
    }
}

前端(JavaScript)实现

1. 页面输入元素

先创建用于输入数据的HTML表单:

<div>
    <input type="text" id="inputName" placeholder="请输入用户名" />
    <input type="email" id="inputEmail" placeholder="请输入邮箱" />
    <button onclick="saveData()">提交数据</button>
</div>

2. 使用jQuery的AJAX实现

确保页面已引入本地jQuery文件:

<script src="Scripts/jquery-3.6.0.min.js"></script>

编写提交数据的JS函数:

function saveData() {
    var userName = $("#inputName").val().trim();
    var userEmail = $("#inputEmail").val().trim();

    // 简单输入验证
    if (!userName || !userEmail) {
        alert("请填写完整信息");
        return;
    }

    // 调用WebForms的WebMethod
    $.ajax({
        type: "POST",
        url: "InsertDataPage.aspx/InsertUserData", // 对应后台页面和方法名
        data: JSON.stringify({ userName: userName, userEmail: userEmail }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(res) {
            if (res.d) { // WebMethod返回结果在res.d中
                alert("数据插入成功!");
                // 清空输入框
                $("#inputName").val("");
                $("#inputEmail").val("");
            } else {
                alert("数据插入失败,请重试");
            }
        },
        error: function() {
            alert("请求出错,请稍后再试");
        }
    });

    // 如果是MVC项目,替换为以下AJAX代码:
    /*
    $.ajax({
        type: "POST",
        url: "/User/InsertUser", // 对应控制器和Action路由
        data: { userName: userName, userEmail: userEmail },
        success: function(res) {
            if (res.Success) {
                alert("数据插入成功!");
                $("#inputName").val("");
                $("#inputEmail").val("");
            } else {
                alert("数据插入失败,请重试");
            }
        },
        error: function() {
            alert("请求出错,请稍后再试");
        }
    });
    */
}

3. 原生JavaScript实现(无jQuery依赖)

如果不想使用jQuery,可使用原生XMLHttpRequest:

function saveData() {
    var userName = document.getElementById("inputName").value.trim();
    var userEmail = document.getElementById("inputEmail").value.trim();

    if (!userName || !userEmail) {
        alert("请填写完整信息");
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "InsertDataPage.aspx/InsertUserData", true);
    xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                var res = JSON.parse(xhr.responseText);
                if (res.d) {
                    alert("数据插入成功!");
                    document.getElementById("inputName").value = "";
                    document.getElementById("inputEmail").value = "";
                } else {
                    alert("数据插入失败,请重试");
                }
            } else {
                alert("请求出错,请稍后再试");
            }
        }
    };

    xhr.send(JSON.stringify({ userName: userName, userEmail: userEmail }));
}

重要注意事项

  • 防止SQL注入:必须使用参数化查询,绝对不能直接拼接SQL语句,避免安全漏洞。
  • 连接字符串管理:将数据库连接字符串配置在Web.config(WebForms)或appsettings.json(ASP.NET Core)中,便于维护和修改。
  • 错误处理:后端需捕获异常并返回明确结果,前端要处理请求失败的情况,给用户友好提示。

内容的提问来源于stack exchange,提问作者fatema

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 07:45:35