Dante Gulapa
Dante Gulapa

Reputation: 111

How to pass object of array to c# web service

I need to pass this json body to my web api post function.

{
    "image_list":[
        {
            "image_name":"sample 1",
            "image_url":"url1",
            "image_description":"desc1"
        },
        {
            "image_name":"sample 2",
            "image_url":"url2",
            "image_description":"desc2"
        }
    ]
}

which data type should i use it in c#? should it be declared as a list in my model class? below is the function that the json will be passed on

   [Route("api/product/create")]
   [HttpPost]
   public HttpResponseMessage CreateProduct([FromBody]ProductModel product)
   {

        String product_id;
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[connection_string].ConnectionString))
        {

            SqlCommand cmd = new SqlCommand("sp_create_product", con);

            // I WANT TO PASS THAT ARRAY OF OBJECTS TO MY STORED PROC HERE
            cmd.Parameters.AddWithValue("product_image_array", product.image_list);

            SqlParameter outputParameter = new SqlParameter();
            outputParameter.ParameterName = "@product_id";
            outputParameter.SqlDbType = SqlDbType.Int;
            outputParameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(outputParameter);

            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();
            cmd.ExecuteNonQuery();

            product_id = outputParameter.Value.ToString();
        }

        var message = Request.CreateResponse(HttpStatusCode.OK, product_id);
        return message;
    }

Upvotes: 0

Views: 518

Answers (1)

D-Shih
D-Shih

Reputation: 46249

You can use this ProductModel to receive your json data.

public class ImageList
{
    public string image_name { get; set; }
    public string image_url { get; set; }
    public string image_description { get; set; }
}

public class ProductModel 
{
    public List<ImageList> image_list { get; set; }
}

Upvotes: 2

Related Questions