Friday 20 May 2016

Data Table to JSON in C#

using Newtonsoft.JSON;

//function for read data from db
 public DataView Get_DataView(string qry)
    {
       string con="your connection string";
        SqlConnection con = new SqlConnection(constr);
        SqlDataAdapter adp;
        try
        {
            con.Open();
            adp = new SqlDataAdapter(qry, con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            DataTable dt = new DataTable();
            DataView dv = new DataView();
            dt = ds.Tables[0];
            dv = dt.AsDataView();
            return dv;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    } 
//in your controller
 DataView dv = UC.Get_DataView("select * from PRODUCT_MAS where STATUS='A'");
                model.productmasterlist = getProductList(dv);
                string JSONString = string.Empty;
                JSONString = JsonConvert.SerializeObject(dv.ToTable());  

No comments:

Post a Comment