返回 JSON 时修改 Controller.View(对象模型) 中的 ActionResult
简短版本:
System.Web.MVC.Controller.View(对象)如何工作?
长版本:
我需要在 JSON 结果前面添加任意字符串(Unparsable Curft)。
我不确定的是如何在 ASP.NET MVC“管道”中修改 ViewResult。我已阅读有关该主题的 MSDN 文档,但我'我仍然不清楚如何解决这个问题。
- 在这种情况下,View(Object) 如何返回 JSON 字符串?
控制器示例
[GridAction]
public ActionResult _SelectBatchEditingGrid(int? id)
{
// GridModel is of type IEnumerable if that matters.
// More info on the GridModel type see: http://www.telerik.com/help/aspnet-mvc/t_telerik_web_mvc_gridmodel_1.html
return View(new GridModel(SessionProductRepository.All())
}
查看示例
<% Html.Telerik().ScriptRegistrar()
.OnDocumentReady(() =>
{%>
/* Protect from setter-property hacks; see https://stackoverflow.com/a/3147804/328397 */
$.ajaxSetup({
converters: {
"text cleanedjson": function(data) {
var jsonString = data.replace("throw 1; <dont be evil> ", "");
return $.parseJSON(jsonString);
} // End function
} // end conveter
}); // end ajaxsetup
- 通过
return View(someObject)
方法在 JSON 数据前面添加字符串的最佳方法是什么?
理想情况下,向每个相关方法添加属性可能是最好的方法,但一旦我了解如何修改 JSON 结果,我就可以通过反射来处理这个问题。
Short version:
How does System.Web.MVC.Controller.View(object) work?
Long version:
I need to prepend my JSON results with an arbitrary string (Unparsable Curft).
The thing I'm unsure of is how I can modify the ViewResult within the ASP.NET MVC "pipeline". I've read the MSDN docs on the subject, but I'm still unclear on how to approach this.
- How does View(Object) return a JSON string in this case?
Controller Sample
[GridAction]
public ActionResult _SelectBatchEditingGrid(int? id)
{
// GridModel is of type IEnumerable if that matters.
// More info on the GridModel type see: http://www.telerik.com/help/aspnet-mvc/t_telerik_web_mvc_gridmodel_1.html
return View(new GridModel(SessionProductRepository.All())
}
View Sample
<% Html.Telerik().ScriptRegistrar()
.OnDocumentReady(() =>
{%>
/* Protect from setter-property hacks; see https://stackoverflow.com/a/3147804/328397 */
$.ajaxSetup({
converters: {
"text cleanedjson": function(data) {
var jsonString = data.replace("throw 1; <dont be evil> ", "");
return $.parseJSON(jsonString);
} // End function
} // end conveter
}); // end ajaxsetup
- What is the best approach to prepend a string to my JSON data, via the
return View(someObject)
method?
Ideally, adding an attribute to each relevant method might be the best way to go, but I can handle this via reflection once I understand how to modify the JSON result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON 只是一个字符串,因此您可以在返回之前以任何方式操作它。不确定是什么请求 JSON,但如果它只是使用 JQuery Post 之类的 AJAX 类型请求,您可以在控制器中执行类似的操作。您不必在操作方法中返回视图。
JSON is just a string so you can manipulate it any way you want before you return it. Not sure what is requesting the JSON, but if it is just an AJAX type request using something like JQuery Post you can do something like this in your controller. You do not have to return a View in your action methods.