-3

I have below table in my SQL Server database:

 ---------------------------
| Id | Title | DecimalDigit |
 ---------------------------
|1   | USD   | 2            |
 ---------------------------
|2   | EUR   | 2            |
 ---------------------------
|3   | JYN   | 4            |
 ---------------------------
|4   | TBH   | 0            |
 ---------------------------

and I want to have this data in client side in a javascript array. My final javascript array would be like this.

var cur=[{id:1 , title:"USD" , decimaldigit:2} , 
         {id:2 , title:"EUR" , decimaldigit:2} , 
         {id:3 , title:"JYN" , decimaldigit:4} , 
         {id:4 , title:"TBH" , decimaldigit:0} 
        ];

How can I retrieve my required data in asp.net and pass them to javascript array?

gotqn
  • 42,737
  • 46
  • 157
  • 243
Behnam
  • 1,039
  • 2
  • 14
  • 39

2 Answers2

1

Try this to building a string, which then can be parse in the client side to JSON:

DECLARE @DataSource TABLE
(
    [ID] INT
   ,[Title] VARCHAR(4)
   ,[DecimalDigit] TINYINT
);

INSERT INTO @DataSource ([ID], [Title], [DecimalDigit])
VALUES (1, 'USD', 2)
      ,(2, 'EUR', 2)
      ,(3, 'JYN', 4)
      ,(4, 'TBH', 0);

SELECT 
'[' +
STUFF
(
    (
        SELECT ',{id:' + CAST([ID] AS VARCHAR(12))  + ', title: "' + [Title]  + '", decimaldigit:' + CAST([ID] AS VARCHAR(12))  +'}'
        FROM @DataSource
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)')
  ,1
  ,1
  ,''
)
+ ']';

enter image description here

gotqn
  • 42,737
  • 46
  • 157
  • 243
0

If you are working in MVC and using Linq then you can return Json value as shown below.

 public ActionResult ConvertDataIntoArray()
 {
     var result = _db.jsonDatas.ToList();           
     return Json(result, JsonRequestBehavior.AllowGet);
 }

Here jsonDatas is the name of table. The returned output will look like as shown below.

[{"Id":1,"Title":"USD","DecimalDigit":2},{"Id":2,"Title":"EUR","DecimalDigit":2},{"Id":3,"Title":"JYN","DecimalDigit":4},{"Id":4,"Title":"TBH","DecimalDigit":0}]

You can further use it in view and manipulate as per your requirement.

piet.t
  • 11,718
  • 21
  • 43
  • 52
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • You can also convert data table to json array. Check this thread https://stackoverflow.com/questions/17398019/convert-datatable-to-json-in-c-sharp – Suraj Kumar Jan 07 '19 at 07:16