MVC从不同的控制器调用视图

use*_*069 19 c# asp.net-mvc

我的项目结构如下:

  • 控制器/ ArticlesController.cs
  • 控制器/ CommentsController.cs
  • 查看/用品/ Read.aspx

Read.aspx采用一个参数说"输出",这是由id及其注释传递的文章的细节 ArticlesController.cs

现在我想写,然后阅读评论:: write()&Read()funct inCommentsController.cs

对于读其评论文章中,我想打电话Views/Articles/Read.aspxCommentsController.cs通过从通过输出参数CommentsController.cs

我怎样才能做到这一点?

UPDATE

代码在这里:

public class CommentsController : AppController
{
    public ActionResult write()
    {
        //some code
        commentRepository.Add(comment);
        commentRepository.Save();

        //works fine till here, Data saved in db
        return RedirectToAction("Read", new { article = comment.article_id });
    }

    public ActionResult Read(int article)
    {   
        ArticleRepository ar = new ArticleRepository();
        var output = ar.Find(article);

        //Now I want to redirect to Articles/Read.aspx with output parameter.
        return View("Articles/Read", new { article = comment.article_id });
    }
}

public class ArticlesController : AppController
{   
    public ActionResult Read(int article)
    {
        var output = articleRepository.Find(article);

        //This Displays article data in Articles/Read.aspx
        return View(output);
    }
}
Run Code Online (Sandbox Code Playgroud)

The*_*Man 54

要直接回答您的问题,如果要返回属于另一个控制器的视图,您只需指定视图的名称及其文件夹名称.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}
Run Code Online (Sandbox Code Playgroud)

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您正在讨论在另一个控制器中使用读写方法.我认为您应该通过模型直接访问这些方法,而不是调用另一个控制器,因为另一个控制器可能返回html.

  • `[InvalidOperationException:视图'文章/索引' 或者找不到它的主人,或者没有视图引擎支持搜索到的位置.我试过这个.它查看/评论/文章/索引.也许这是使用区域的结果.`return View("../ Articles/Index")`工作. (4认同)
  • 如果你选择`〜/ Views/Articles/Index.cshtml`,你也可以从根开始,以另一种方式工作 (2认同)