我使用下拉列表作为webmethod中通过AJAX调用的sql查询的过滤器。如果未选择任何内容,则下拉选项可以是数字(1,2,3,4 ...)或“”作为默认选项。因此,查询如下:
SELECT region, customer FROM Tregion WHERE (@fkidregion is null or fkidregion = @fkidregion)
如果在下拉列表中没有选择任何内容(“”),则在查询中传递null,如果不是,则使用选项编号。在AJAX调用中,我使用以下内容传递下拉值:
JSON.stringify({ 'fkidregion': $('[id$=ddlRegion]').val() })
如果进行选择,这可以正常工作,但如果选择了默认的“”选项,则查询无法正确执行:
exec sp_executesql N'SELECT region, customer FROM Tregion WHERE (@fkidregion is null or fkidregion = @fkidregion)',N'@fkidregion nvarchar(4000)',@fkidregion=N''
但它应该是这样的:
exec sp_executesql N'SELECT region, customer FROM Tregion WHERE (@fkidregion is null or fkidregion = @fkidregion)',N'@fkidregion nvarchar(4000)',@fkidregion=NULL
所以我的问题是如何在JSON数据中传递空值或指示空值应该用于空字符串。
如果需要,以下是代码:
[System.Web.Services.WebMethod]
public static BOPData[] PopulateBOPDataFields(string fkidregion)
{
DataTable dt = new DataTable();
List<BOPData> list = new List<BOPData>();
String strConnString = ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString;
String strQuery = @"SELECT region, customer FROM Tregion WHERE (@fkidregion is null or fkidregion = @fkidregion)";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@fkidregion", fkidregion);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
foreach (DataRow dtrow in dt.Rows)
{
BOPData data = new BOPData();
data.region = dtrow["region"].ToString();
data.customer = dtrow["customer"].ToString();
list.Add(data);
}
}
}
return list.ToArray();
}
public class BOPData
{
public string region { get; set; }
public string customer { get; set; }
}
AJAX功能:
function PopulateBOPDataFields() {
$.ajax({
type: "POST",
url: pageUrl + '/PopulateBOPDataFields',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'fkidregion': $('[id$=ddlRegion]').val() }),
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$('[id$=gvBOP]').append(
"<tr><td>" + data.d[i].region
+ "</td><td>" + data.d[i].customer
+ "</td></tr>");
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}