I want to do the following steps:
- Take a list of check box values and make them into a string array in JavaScript.
- Take the array and send it to a server-side function.
- Take the array server side and make it into DataTable.
- Take the DataTable and send it as a TVP to a stored procedure.
I've gotten this to work from server-side on. Where I have trouble is going from JavaScript to server.
With my current code, I get this error:
There are not enough fields in the Structured type. Structured types must have at least one field.
How can I pass the JavaScript array to a web method?
<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;
}
}
}
If this is a complete asinine way to do it, revisions are more than welcome :)