问题
I have the following code that returns a List
in CVS
format using Content
, which is working fine.
public ContentResult LearningActionMonitoringPageDataAsync(int actionId)
{
//other code
using (var stream = new MemoryStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(resultsToReturn);
writer.Flush();
stream.Position = 0;
text = reader.ReadToEnd();
}
return Content(text, "text/csv");
}
But, what I want to do is, instead of returning the Content
, putting it inside another object which contains some other information to be returned, something like this:
List <PageData> pageData = new List <PageData> {
CSVcontent = Content(text, "text/csv"),
PageTitle = "Abc",
//some other data to display on the page
}
However, I could not manage to do it. Any help?
回答1:
This can be achieved by returning an ActionResult
with the Json
method, e.g:
List <PageData> pageData = new List <PageData> {
CSVcontent = Content(text, "text/csv"),
PageTitle = "Abc",
//some other data to display on the page
}
return Json(pageData, JsonRequestBehaviour.AllowGet);
Note that if your CSV data is now not the "main" return from the HTTP method, there's no need to have the Content()
call, you can just assign it directly, e.g.:
`CSVContent = text`
But it will be up the client to work with that data. Using Json()
will automatically set the content type appropriate for JSON
.
来源:https://stackoverflow.com/questions/57144160/how-to-put-content-object-in-controller-inside-another-object-to-be-returned