简体   繁体   English

如何告诉MVC 4视图返回带有子路由的JSON结果

[英]How to tell an MVC 4 View to return a JSON result with a sub route

What I want is a solution for the next problem: 1. I have an MVC 4 view + controller that renders Index and another for Details 2. to access that information I go to http://localhost:1234/Movies and to http://localhost:1234/Movies/1 (for details) 3. I want to create a new route http://localhost:1234/json/Movies and http://localhost:1234/json/Movies/1 4. in the Method of Index I want the code to be like: 我想要的是下一个问题的解决方案:1.我有一个MVC 4视图+控制器,它呈现索引,而另一个用于呈现Details。2.访问该信息,我去http://localhost:1234/Movieshttp://localhost:1234/Movies/1 (有关详细信息)3.我想创建一个新路由http://localhost:1234/json/Movieshttp://localhost:1234/json/Movies/1 4.在我希望代码的索引方法如下:

public ActionResult Index(string format)
        {
            return View(db.Movies.ToList());
        }

or 要么

public ActionResult Index(string format)
        {
            return ChooseView(db.Movies.ToList());
        }

and I want the view to render the corrent (html\\json) according to the route. 我希望视图根据路线呈现相应的(html \\ json)。

Is that possible? 那可能吗?

Thanks. 谢谢。

In your controller 在您的控制器中

public class MoviesController : Controller
{
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Index(string format)
    {
        return ToResult(db.Movies.ToList(), format);
    }
}

This will make /Movies get the HTML page rendered by the view Index.cshtml and /Movies?format=json get the list of movies as JSON data. 这将使/Movies获取由视图Index.cshtml呈现的HTML页面,而/Movies?format=json获取作为JSON数据的电影列表。

Helper method 辅助方法

public static ActionResult ToResult(object data, string format)
{
    if (format == "json")
    {
        return Json(data, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return View(data);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM