MVC Вызов представления с другого контроллера

Моя структура проекта похожа:

  • Контроллеры /ArticlesController.cs
  • Контроллеры /CommentsController.cs
  • Просмотров/Статьи/Read.aspx

Read.aspx принимает параметр say "output", который является деталями статьи по id и ее комментариям, переданным из ArticlesController.cs

Теперь я хочу написать, а затем читать комментарии:: write() и Read() funct в CommentsController.cs

Для чтения статьи с ее комментариями я хочу вызвать Views/Articles/Read.aspx из CommentsController.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);
    }
}

Ответы

Ответ 1

Чтобы ответить на свой вопрос, если вы хотите вернуть представление, принадлежащее другому контроллеру, вам просто нужно указать имя представления и его имя папки.

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

и

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Кроме того, вы говорите об использовании метода чтения и записи с одного контроллера в другом. Я думаю, вам следует напрямую обращаться к этим методам с помощью модели, а не обращаться к другому контроллеру, поскольку другой контроллер, вероятно, возвращает html.

Ответ 2

Вы можете переместить представление read.aspx в общую папку. Это стандартный способ в таких обстоятельствах

Ответ 3

Я не уверен, правильно ли получил ваш вопрос. Может быть, что-то вроде

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}