I'm using ASP.NET MVC and I have a model class which represents a peice of data which is associated to an entity but created by another. For example, given the following ViewM开发者_JS百科odels,
public class User {
public int UserId { get; set; }
public IEnumerable<NewsComment> Comments { get; set; }
}
public class News {
public int NewsId { get; set; }
public string News { get; set; }
public IEnumerable<NewsComment> Comments { get; set; }
}
public class NewsComment {
public int NewsCommentId { get; set; }
public string Comment { get; set; }
public int NewsId { get; set; }
public int UserId { get; set; }
}
public class NewsController : Controller
{
public ActionResult Index()
{
return View(ListAllNews());
}
public ActionResult Detail(int newsId)
{
return View(GetNewsItem(newsId));
}
}
public class NewsCommentController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public void Create()
{
int newsId = Request["news_id"];
int userId = Request["user_id"];
string comment = Request["comment"];
SaveNewsComment(newsId, userId, comment);
return RedirectToAction("Detail","News",new { newsId = newsId });
}
}
If I'm only ever displaying comments on the News/Detail view or the User/Detail view and comments are posted on the News/Detail view then
- Is there a need for a NewsCommentController?
- Should NewsCommentController only have a Create action which is called from and redirects back to the NewsController/Detail action once that method is complete?
- Should I be using
RenderAction
to list my comments out from NewsCommentController? - Or can all this be done from within either NewsController or UserController, whichever is appropriate?
If your News/Detail view posts new comments, then you needn't have a NewsCommentController. Your NewsComment
class is not a ViewModel on its own.
精彩评论