Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a single DataRow object from Asp Web API?

So I am writing some Asp.Net WebApi code to hook with old C# back-end code where there is no model class used. (Pure dataTable returned from DataAccess, Crazy right? I know)

Following is the code I put on the Server side.

 public IHttpActionResult GetProduct(int campaignID, int productID)
    {
        var so = new SearchOptions(campaignID)
        {
            ProductID = productID
        };

        var result = SearchManager.Search(so);
        if (result == null || result.Rows.Count == 0)
            return NotFound();
        return Ok(result.Rows[0]);

    }

I am expecting to have the response like this:

{
Field1: "field1",
Field2: "field2",
...
}

But Actually I am having this:

{
  "rowError": "",
  "rowState": 2,
  "table": [
    {
      Field1 : "field1",
      Field2 : "field2",
      ...
    }
  ],
  "itemArray": ["field1","field2"],
  "hasErrors": false
}

I don't want all these rowError, rowState...etc

If I am doing this on the server side:

public IHttpActionResult GetProduct(int campaignID, int productID)
        {
            var so = new SearchOptions(campaignID)
            {
                ProductID = productID
            };

            var result = SearchManager.Search(so);
            if (result == null || result.Rows.Count == 0)
                return NotFound();
            return Ok(result);

        }

I am receiving this:

[{Field1: "field1", Field2: "field2"..}]

which is unfortunately rejected by ngResource get method since it is an array rather than a single Json Object.

What should I do? If I just want to return a single dataRow as a Json string.

Ideally I want to avoid go down to the path of creating an Response Object as suggested by Manoz. (Thank you for your answer Manoz though)

Thanks

like image 828
TypingPanda Avatar asked Oct 18 '22 02:10

TypingPanda


1 Answers

You can convert your DataRow to Dictionary using LINQ:

public IHttpActionResult GetProduct(int campaignID, int productID)
{
    var so = new SearchOptions(campaignID)
    {
        ProductID = productID
    };

    var result = SearchManager.Search(so);
    if (result == null || result.Rows.Count == 0)
        return NotFound();

    var row = result.Rows[0];
    return Ok(row.Table.Columns
        .Cast<DataColumn>()
        .ToDictionary(c => c.ColumnName, c => row[c]));
}

That action returns JSON as you want: { Field1: "field1", Field2: "field2", ... }

like image 197
feeeper Avatar answered Nov 14 '22 15:11

feeeper