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

在ASP.NET中使用存储过程插入数据无结果,求排查缺失环节

Hey there! Let's break down what might be going wrong with your ASP.NET + AJAX + stored procedure setup—since you're new to this, let's go step by step to track down the issue.

1. First, fix up your AJAX request to catch errors

Your current JS code is incomplete, so let's add critical bits that will help you see what's failing. The biggest mistake new devs make here is skipping the error callback, which hides request failures entirely.

function referFriend() { 
  var user = $("input#name").val(); 
  $.ajax({ 
    type: 'POST', 
    url: '/fix/sendinfo.aspx', 
    // Make sure your parametros JSON is complete and valid
    data: { 
      funcion: "referFriend", 
      parametros: JSON.stringify({ UserName: user }) 
    },
    dataType: 'json', // Tells jQuery to expect JSON back from the server
    success: function(response) {
      console.log("Request succeeded:", response);
      alert(response.Message); // Optional: give user feedback
    },
    error: function(xhr, status, error) {
      // This will show you exactly what went wrong in the browser console
      console.error("AJAX Error:", status, error);
      console.log("Server response:", xhr.responseText);
    }
  });
}

Open your browser's dev tools (F12), go to the Network tab, and watch the request fire—you'll see if it's failing to reach the server, or if the server is returning an error.

2. Validate your ASP.NET backend logic

Your sendinfo.aspx page needs to properly handle the POST request, parse the JSON parameters, and call the stored procedure correctly. Here's a robust example:

protected void Page_Load(object sender, EventArgs e)
{
    // Only handle POST requests
    if (Request.HttpMethod == "POST")
    {
        string funcion = Request.Form["funcion"];
        string parametros = Request.Form["parametros"];

        if (string.Equals(funcion, "referFriend", StringComparison.OrdinalIgnoreCase))
        {
            // Parse the JSON parameters (use Newtonsoft.Json or System.Text.Json)
            var friendData = Newtonsoft.Json.JsonConvert.DeserializeObject<FriendReferralModel>(parametros);
            
            // Call the method to execute the stored procedure
            bool saveSuccess = SaveReferralToDatabase(friendData.UserName);
            
            // Send a clear response back to the frontend
            Response.ContentType = "application/json";
            Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new {
                Success = saveSuccess,
                Message = saveSuccess ? "Referral saved!" : "Failed to save referral"
            }));
            Response.End(); // Stop page processing after sending the response
        }
    }
}

// Model to match your JSON parameters
public class FriendReferralModel
{
    public string UserName { get; set; }
}

// Method to execute the stored procedure
private bool SaveReferralToDatabase(string userName)
{
    // Use your actual connection string from Web.config
    string connString = ConfigurationManager.ConnectionStrings["YourDatabaseConn"].ConnectionString;
    
    using (SqlConnection conn = new SqlConnection(connString))
    {
        using (SqlCommand cmd = new SqlCommand("YourStoredProcedureName", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            // Match the parameter name EXACTLY to what's in your stored procedure
            cmd.Parameters.AddWithValue("@UserName", userName);

            conn.Open();
            int rowsAffected = cmd.ExecuteNonQuery();
            
            // For insert operations, rowsAffected > 0 means success
            return rowsAffected > 0;
        }
    }
}

Key checks here:

  • Make sure your connection string in Web.config is correct (no typos in server name, database name, or credentials)
  • Double-check that the parameter name (@UserName) matches exactly what's defined in your stored procedure
  • Use using statements to automatically clean up database connections/commands (prevents leaks)
3. Test your stored procedure directly

Sometimes the issue isn't with your code—it's with the stored procedure itself. Run this directly in SQL Server Management Studio to verify it works:

EXEC YourStoredProcedureName @UserName = 'TestUser'

If no data gets inserted, check:

  • Does the stored procedure have a valid INSERT statement? (No typos in table/column names)
  • Is there a transaction that's not being committed?
  • Are there conditional checks (like duplicate data) that are silently blocking the insert without returning an error?
4. Verify frontend parameters are being passed correctly

In your browser's dev tools Network tab, click on the POST request to sendinfo.aspx and check the Form Data section. Confirm:

  • The funcion value is exactly referFriend
  • The parametros JSON is valid (no missing brackets or quotes)
  • The UserName value matches what you entered in the input field

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:53:50