开发者

MVC3 Routing Issues - How to re-use a View for all Controller Methods?

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.


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.

return View("SharedJsonView");

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜