I am using asp.net core. I need to display the data in the select dropdown in react from web api. WebApi GET method that returns SQL DataReader. Reader returns one row with prodid, prodname, and proddescr columns. Please help what the best way to write a get web api that uses SQL DataReader for filling the select dropdown in react.
[HttpGet("{ProductID}")]
public JsonResult GetProductInfo(int ProductID)
{
var response = GetProductInfo(ProductID);
return new JsonResult(response);
}
public string GetProductInfo(int Product_ID)
{
SqlConnection objConnect = new SqlConnection(_connectionString);
SqlCommand objCommand = new SqlCommand("usp_GetProdInfo", objConnect);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add(new SqlParameter("@Product_ID", SqlDbType.Int, 4));
objCommand.Parameters["@Product_ID"].Value = intProduct_ID;
string json = string.Empty;
List<object> objects = new List<object>();
objConnect.Open();
SqlDataReader reader = objCommand.ExecuteReader();
while (reader.Read())
{
IDictionary<string, object> record = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
record.Add(reader.GetName(i), reader[i]);
}
objects.Add(record);
}
json =JsonConvert.SerializeObject(objects);
reader.Close();
objConnect.Close();
return json;
}
you don't need to serialize data, Net can do it for you. And it is a very bad programming style to use objects instead of real classes. So return List instead of List
public ActionResult<List<Product>> GetProductInfo(int ProductID)
{
var response = GetProductInfoList(ProductID);
if (response != null) return Ok(result)
else retun BadRequest();
}
public List<Product> GetProductInfoList(int Product_ID)
{
List<Product> products = new List<Product>();
...fix the code to get typed List<Product> from reader
return products;
}