I have a MVC5 project where we're creating an IMDB style clone. It's for games, movies and books instead of just movies.
The page has Review Feed, where you are shown a list of all Reviews, you can also add new reviews.
When I click on a review, I get to that reviews details page (~Views/Reviews/Details.cshtml), and so far so good. It shows all the details, no problems.
In the Reviews/Details view, I want to add a comment section. So I added this to my Review/Details.cshtml page:
<h4>Comments</h4>
@{
Html.RenderPartial("_CommentPartial");
}
@foreach (var comment in Model.CommentToReviews)
{
<div class="row">
<div class="col-xs-2">
@Html.Raw(comment.User.Username)
<br />
posted at: @Html.Raw(comment.CreatedDate.ToShortDateString())
</div>
<div class="col-xs-10">
@Html.Raw(comment.Comment)
</div>
</div>
}
The problem is that I'm not sure how to pass on the current review-ID to the create-comment partial view.
This is the partial:
@model gmbdb.CommentToReview
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add a comment</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Comment, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Comment, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Comment, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
And this is the Create get/post methods in CommentToReviewsController,
Get:
public ActionResult Create(Guid reviewId)
{
var newComment = new CommentToReview();
newComment.UserId = ((User) Session["currentUser"]).Id;
newComment.ReviewId = reviewId;
return View(newComment);
}
Post:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,UserId,ReviewId,Comment,CreatedDate")] CommentToReview commentToReview)
{
if (ModelState.IsValid)
{
commentToReview.Id = Guid.NewGuid();
commentToReview.CreatedDate = DateTime.Now;
//find current Review and add this comment to that review
foreach (var review in db.Reviews)
{
if (review.Id == commentToReview.ReviewId)
{
review.CommentToReviews.Add(commentToReview);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
ViewBag.ReviewId = new SelectList(db.Reviews, "Id", "Title", commentToReview.ReviewId);
ViewBag.UserId = new SelectList(db.Users, "Id", "Username", commentToReview.UserId);
return View(commentToReview);
}