在 C# 函数中使用 JSONResult
我有一个以下面的方式返回 JsonResult 的函数。
var attachments = (from a in ar.Attachments
select new { id = a.Id, filename = a.FileName }).ToArray();
var result = new
{
comments = "Some string",
attachments = attachments
};
return this.Json(result);
我需要在另一个类中使用这个结果,我需要访问“评论”和“附件”。这里附件是一个字符串数组,注释是一个字符串。请让我知道我该怎么做。
I have a function which returns a JsonResult in the below way.
var attachments = (from a in ar.Attachments
select new { id = a.Id, filename = a.FileName }).ToArray();
var result = new
{
comments = "Some string",
attachments = attachments
};
return this.Json(result);
I need to use this result in another class where I need to access the "comments" and "attachments". Here attachments is a string array and comments is a string. Please let me know how I can do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为结果创建一个 ViewModel,然后重用该类。 ViewModel 的全部内容只是 POCO 或 DTO。这个想法是,它为您提供了一种不同的方式来“查看”数据,实际上没什么特别的。
所以你最终得到了 3 个部分。
获取数据方法:
您的控制器方法:
您的其他方法将直接调用 GetViewModel()。这将为您将其分开一点。
You could create a ViewModel for the result and then just reuse that class. All a ViewModel is, is just a POCO or DTO. The idea is that it gives you a different way to "look" at your data, nothing special really.
So you end up with 3 parts.
The get data method:
Your controller method:
And your other method would just call GetViewModel() directly. This would separate this out a bit for you.
好的,所以这是一个我认为应该使用
dynamic
类型满足您需求的答案...这是您在控制器上调用的方法...我已经放入了“硬编码”示例数据根据您对此示例的要求...我从注释中删除了“s”,只是因为:
直接调用控制器操作并读取 JsonResult 的代码:
Ok, so here is an answer that I believe should fit your needs using the
dynamic
type...This is the method you call on the controller...I have put in 'hard coded' sample data as per your requirements for this example...I've removed the 's' from comments just because:
The code that calls the controller action directly and reads the JsonResult: