Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Using a JavaScript Array as a Table valued Parameter for SQL Server Stored Procedure

$
0
0

I have a simple but of JavaScript that creates two 'person' objects.  These person objects have two properties: FirstName and LastName.  I have a table in my SQL Server database with the same columns as properties of the person object.  I need to be able to create an array of person objects and insert them into the 'Names' table (which has two columns: FirstName and LastName.  To do this I decided to the following:

CREATE TYPE dbo.NameList ASTABLE( FirstName NVARCHAR(255), LastName NVARCHAR(255));

CREATEPROCEDURE dbo.InsertNames_ByTVP@Names AS dbo.NameList READONLYASBEGINSET NOCOUNT ON;INSERT dbo.Names(FirstName, LastName)SELECT FirstName, LastName FROM@Names;END
GO

Here's the WebMethod I'm using: (I have a Person class with the same properties as the JavaScript object below).

public class Service : System.Web.Services.WebService
    {

        [WebMethod]
        public void InsertPeople(string personList)
        {
            
            var jss = new JavaScriptSerializer();
            var list = jss.Deserialize<List<Person>>(personList);
            DataTable dt = new DataTable();
            dt.Columns.Add(list[0].FirstName);
            dt.Columns.Add(list[0].LastName);
            foreach (var p in list)
            {
                dt.Rows.Add(p.FirstName, p.LastName);
            }
            string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            using (var con = new SqlConnection(cs))
            {
                using (var cmd = new SqlCommand("spInsertPeople",con))
                {
                    con.Open();
                    cmd.Parameters.AddWithValue("@Names", dt);
                    cmd.ExecuteNonQuery();

                }
            }
        }
    }


This creates a datatable with the same columns as the person object has properties.  Now finally for the JavaScript:

$(document).ready(function ()
        {
            var personList = new Array();
            var person = {};
            person.FirstName = "TestFirstName";
            person.LastName = "TestLastName";
            var person2 = {};
            person2.FirstName = "TestOtherFirstName";
            person2.LastName = "TestOtherLastName";

            personList.push(person);
            personList.push(person2);
            var data = { 'personList': personList };
            $('#btnSubmit').click(function ()
            {
                console.log(JSON.stringify(data));
                $.ajax(
                {
                    type: "POST",
                    url: "Service.asmx/InsertPeople",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: data,
                    success: function (data)
                    {
                        console.log(data.d);
                    },
                    error: function (xhr)
                    {
                        console.log(xhr.status);
                    }

                });
            });
        });

If I do this and don't JSON.stringify the data transfer object I get an error about invalid JSON primitive.  If I DO stringify the DTO I get.  "{"Message":"Type \u0027System.String\u0027 is not supported for deserialization of an array.","StackTrace":""

I've been trying to figure this out for a couple days now and I'm lost at what else to try.  How can I deserialize this JS into a list of C# objects?



Viewing all articles
Browse latest Browse all 31927

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>