我的项目结构如下:
Read.aspx接受一个名为"output“的参数,该参数是从ArticlesController.cs
传递来的文章的id及其注释的详细信息
现在,我想在CommentsController.cs
中编写并阅读comment::write()
& Read()
函数
为了阅读这篇带有注释的文章,我想通过从CommentsController.cs
传递输出参数来从CommentsController.cs
调用Views/Articles/Read.aspx
我该怎么做呢?
更新
代码如下:
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);
}
}
发布于 2012-08-02 14:46:46
要直接回答您的问题,如果您想返回一个属于另一个控制器的视图,您只需指定该视图的名称及其文件夹名称。
public class CommentsController : Controller
{
public ActionResult Index()
{
return View("../Articles/Index", model );
}
}
和
public class ArticlesController : Controller
{
public ActionResult Index()
{
return View();
}
}
此外,您还在讨论如何在一个控制器中使用另一个控制器中的读写方法。我认为你应该通过一个模型直接访问这些方法,而不是调用另一个控制器,因为另一个控制器可能会返回html。
发布于 2012-08-02 15:22:17
您可以将read.aspx视图移动到共享文件夹。这是在这种情况下的标准方式。
发布于 2012-08-02 15:11:01
我不太确定我是否把你的问题弄对了。也许是像这样的
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's 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);
}
}
https://stackoverflow.com/questions/11772072
复制相似问题