[英]Pass JavaScript array to server-side function with jQuery
我要执行以下步骤:
我已经从服务器端开始工作了。 我遇到麻烦的地方是从JavaScript到服务器。
用我当前的代码,我得到这个错误:
结构类型的字段不足。 结构化类型必须至少具有一个字段。
如何将JavaScript数组传递给Web方法?
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;
using System.Web.Services;
namespace SendTVP
{
public partial class _default : System.Web.UI.Page
{
//page variables
string filterList = string.Empty;
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spFilterPatientsByRace",con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
//required for passing a table valued parameter
param.SqlDbType = SqlDbType.Structured;
param.ParameterName = "@Races";
//adding the DataTable
param.Value = dt;
cmd.Parameters.Add(param);
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
[ScriptMethod]
[WebMethod]
//this method will take JS array as a parameter and turn it into a DataTable
public void TableFilter(string filterList)
{
DataTable filter = new DataTable();
filter.Columns.Add(new DataColumn() { ColumnName = "Races" });
dt.Columns.Add(new DataColumn() { ColumnName = "Races" });
foreach (string s in filterList.Split(','))
{
filter.Rows.Add(s);
}
dt = filter;
}
}
}
如果这是完成问题的完整方法,那么欢迎进行修订:)
这里的问题是您的Web表单上有两种方法需要回发周期。
WebMethod
,它将创建_default
类的实例并设置dt
变量,但不对其进行任何处理。 Button1_Click
,将创建_default
类的新实例,因此dt
变量设置为new DataTable();
。 因此,您的参数没有列或其他数据。 您将要用一种方法(大概是TableFilter
方法)来处理DataTable
。
我建议使用JSON (它是javascript的子集)来表示您要传递的数据。 JSON的示例为:
[ "string1", "string2" ]
要么
{ "property1": "a", "property2": "b" }
当第一个是有效的javascript数组,第二个是有效的javascript对象,当它直接通过<script>
标记传递给浏览器时。 JQuery有多种处理JSON的方法,您可以在.NET端查看JSON.NET或ServiceStack.Text ,以将JSON反序列化为C#对象。
[编辑]
尽管我应该指出,很难将JSON反序列化到C# DataTable
因为DataTable
具有很多不必要在客户端上需要的属性。 最好的选择是反序列化为List<T>
并遍历该列表,并根据需要添加到DataTable
行中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.