开发者

Read a Property from an anonymous-typed JSON result

Hi in a Action I create Json data like so:

public JsonResult InvoiceLineGridData(string sidx, string sord, int page, int rows, int id)
         {
            ....

                var jsonData = new {
                total = totalPages,
                page,
                records = totalRecords,
                rows = invoiceLines.Select(............)
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

In the method that calls this I want to get the number of records from this data.

Could this be a problem because it's an anonymous type?

I go :

var result = controller.InvoiceLineGridD开发者_StackOverflowata(null, "desc", 1, 10, 7);

result.Data

but I can't seem to get the total number of records out. Anybody know how to do this?


Yes, this is because Data is just an object. If you are doing this in the same assembly as your controller, you could create a dynamic and get the data from it. But your best bet, if you're actually hoping to use data this way, is to create a real (non-anonymous) type to which you can cast the Data in your test method.

var jsonData = new InvoiceLineData {
            Total = totalPages,
            Page,
            Records = totalRecords,
            Rows = invoiceLines.Select(............)
        };


var resultData = (InvoiceLineData)result.Data;
// or
dynamic resultData = result.Data;

Assert.AreEqual(10, resultData.Records);

As I look at this more, it looks like your data is probably following a specific pattern expected by some kind of general grid control. You would do well to formalize this in a GridData class and use that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜