Return Multiple Objects Using ASP.NET MVC'S JsonResult Class
Asked Answered
S

3

6

Is it possible to Multiple Objects Using ASP.NET MVC'S JsonResult Class.... Here is a controller method which returns json object of my records but i also want to pass the count value....

var materials = consRepository.FindAllMaterials().AsQueryable();
var count = materials.Count();
var results = new PagedList<MaterialsObj>(materials, currentPage-1, pageSize);
return Json(results);

How to return count along with the results from asp.net mvc controller....

Spicy answered 4/5, 2010 at 12:7 Comment(0)
C
20

How about creating an anonymous type and JSON'ing that?

e.g.

var resultCount = results.Count;
var genericResult = new { Count = resultCount, Results = results };
return Json(genericResult);

You can then eval your json string in your script as before but just query the Count and Results properties on your eval result.

Couscous answered 4/5, 2010 at 12:19 Comment(4)
My assumption was you were calling the eval function yourself. If you've done a jQuery call specifying a json result type, it will already have done that.Couscous
@Oscar that is true for this case, but in cases where the data you want to obtain isn't a simple property, you would need to pass an object like Neil has demonstrated.Haiphong
how to read Count and Results in the ajax success property?Pillory
@RehanKhan , check this to read Count and Results in the ajax success. Hope helps.Myrtlemyrvyn
N
0

There is a way to send multiple objects which are dynamically identified to send. See this.

Natheless answered 29/2, 2012 at 13:41 Comment(1)
Please instead of just linking to a blog include at least a summary of the answer here. By doing that your answer does not become invalid should the blog ever go offline. It makes your answer nicely self-contained. You can still link to the blog for further details.Gahan
U
0

In C# part:

Using new keywork

var genericResult = new { homeworkData = homework, attachmentData = homeworkAttachment };
var result = this.Json(genericResult, JsonRequestBehavior.AllowGet);
return result;

In jquery side :

function getHomewrokDetailResponse(dataSent, result) {
if (result && result.homeworkData) {
    homeworkId = result.homeworkData.homeworkId;

    ....
}
 if (result && result.attachmentData) {
    xy = result.attachmentData.xyz;

    ....
}
Umeko answered 1/2, 2017 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.