MVC3 路由问题 - 如何为所有控制器方法重用视图?
我正在尝试在 MVC3 中实现一个通用控制器来返回各种 JSON 提要,例如 -
public class AjaxController : Controller
{
public ActionResult Feed1()
{
ViewBag.Json = LogicFacade.GetFeed1Json();
return View();
}
public ActionResult Feed2()
{
ViewBag.Json = LogicFacade.GetFeed2Json();
return View();
}
}
这个类中有 30 多个方法,问题是这需要为写出 ViewBag 的每个控制器方法实现一个相同的视图(叹气) .杰森。
我假设这是一个路由问题,但我正在努力解决这个问题。以下不起作用 -
- 尝试设置 ViewBag.Json 然后使用 RedirectToAction() 但这似乎重置了 ViewBag.Json。
- 注意 JsonResult 不适合我的需求,我使用不同的 JSON 序列化器。
因此,这里的目标是维护一个视图文件,但让此类具有由路由调用的单独方法,而不是蹩脚的 switch 语句实现。
任何帮助表示赞赏。
I'm trying to implement a common controller in MVC3 to return various JSON feeds, example -
public class AjaxController : Controller
{
public ActionResult Feed1()
{
ViewBag.Json = LogicFacade.GetFeed1Json();
return View();
}
public ActionResult Feed2()
{
ViewBag.Json = LogicFacade.GetFeed2Json();
return View();
}
}
This class has 30+ methods in it, the problem is this requires implementing an IDENTICAL View for each of the Controller's methods (sigh) that writes out ViewBag.Json.
I'm assuming this is a routing issue but I'm struggling with that. The following didn't work -
- Tried setting ViewBag.Json then using RedirectToAction() but that seems to reset ViewBag.Json.
- Note JsonResult is not appropriate for my needs, I'm using a different JSON serialiser.
So the objective here is to maintain one View file but keep this class with seperate methods that are called by routing, and not a crappy switch statement implementation.
Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用相同的视图并只需指定名称。如果仅由一个控制器使用,您可以存储在控制器的视图文件夹中;如果由多个控制器使用,则可以存储在共享视图文件夹中。
另一个也许更好的解决方案是创建您自己的结果(可能从 JsonResult 派生,也可能直接从 ActionResult 派生),从而创建您需要的 JSON 响应。查看 http://www.codeplex.com/aspnet 上的 JsonResult 源代码,了解如何实现的想法去做它。
Use the same view and just specify the name. You can store in the controller's view folder, if only used by one controller, or in the Shared view folder if used by more than one.
Another, perhaps better, solution would be to create your own result -- maybe deriving from JsonResult, maybe directly from ActionResult -- that creates the JSON response that you need. Look at the source code for JsonResult on http://www.codeplex.com/aspnet for ideas on how to do it.