// 前端
$.ajax({
type: "POST",
url: "addXZYW.aspx/SetBaoCun",
data: "{id:'" + id + "',mc:'" + mc + "'...}", // 手動拼接 JSON 字符串
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// 後台
[WebMethod]
public void SetBaoCun(string id, string mc, ...) { ... }
contentType: "application/json" 告訴服務端請求體是 JSON,但 ASP.NET WebMethod 默認綁定器期望 application/x-www-form-urlencoded 或 multipart/form-data 格式,導致模型綁定失敗,參數全為 null。
// 前端
$.ajax({
type: "POST",
url: "addXZYW.aspx/SetBaoCun",
data: { id: id, mc: mc, engname: engname, shuruma: shuruma, tym: tym }, // 對象,jQuery 自動序列化為 form-urlencoded
// contentType 默認即為 application/x-www-form-urlencoded
dataType: "json"
});
// 後台無需改動,或改用 FormCollection
[WebMethod]
public void SetBaoCun(string id, string mc, ...) { ... }
// 前端保持原樣
// 後台
[WebMethod]
public void SetBaoCun(string json) { // 接收原始 JSON 字符串
var obj = JsonConvert.DeserializeObject(json);
// 使用 obj.Id, obj.Mc ...
}
public class ParamModel {
public string Id { get; set; }
public string Mc { get; set; }
// ...
}
application/x-www-form-urlencoded:自動映射同名參數(id=1&mc=test → string id, string mc)。application/json:不支持 直接映射到多個 string 參數,只能接收單一對象參數或原始字符串。HttpModule 或遷移至 ASP.NET Core / Web API。原代碼 SQL 拼接 string.Format("values({0},{1}...)", id, mc...) 存在嚴重 SQL 注入漏洞。務必使用參數化查詢:
string sql = "INSERT INTO zsk_yaopin(id,name,engname,shuruma1,commonname) VALUES(@id,@mc,@eng,@shu,@tym)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@mc", mc);
// ...
cmd.ExecuteNonQuery();