MVC Calling a view from a different controller

Viewed 117812

My project structure is like:

  • Controllers/ArticlesController.cs
  • Controllers/CommentsController.cs
  • Views/Articles/Read.aspx

Read.aspx takes a parameter say "output", which is the details of the article by id and its comments, passed from ArticlesController.cs

Now I want to write then read the comment:: write() & Read() funct in CommentsController.cs

For reading the article with its comments, I want to call Views/Articles/Read.aspx from CommentsController.cs by passing output parameter from CommentsController.cs

How can I do this?

UPDATE

Code Here:

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);
    }
}
4 Answers

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

Related