My project structure is like:
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?
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);
}
}
This question is related to
c#
asp.net-mvc
I'm not really sure if I got your question right. Maybe something like
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);
}
}
You can move you read.aspx view to Shared folder. It is standard way in such circumstances
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.
Source: Stackoverflow.com