views:

30

answers:

1

Hi,

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 ViewModels,

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

  1. Is there a need for a NewsCommentController?
  2. Should NewsCommentController only have a Create action which is called from and redirects back to the NewsController/Detail action once that method is complete?
  3. Should I be using RenderAction to list my comments out from NewsCommentController?
  4. Or can all this be done from within either NewsController or UserController, whichever is appropriate?
+2  A: 

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.

So NewsController could have a CreateComment action?
Rob Stevenson-Leggett
Yes. There's no hard and fast rule that each model class must have a corresponding view.