kenalex
kenalex

Reputation: 61

display comments and post form on the same page to add new comments

I am building a web application in ASP.NET MVC. I have a comment page where comments are displayed in a list with the latest to oldest and also have a form at the bottom where a user can post new comments. Form entries should also be highlighted in addition to having the page displaying the latest comments.

Whats the best way to do this, where displayed data and a post form are on the same page?

Is it possible to do this without ajax as well ?

--Code extract--

class CommentsViewModel
{
   public IList<Comment> comments { get; set; }
    public Comment comment { get; set; }
    public SelectList commentCategories { get; set; }
 }


class Comment
{
    [Required]
    public string commentData { get; set; }

    [Required]
    public int? commentCategory { get; set; }
}


class Comments : Controller
{

    public ActionResult Index()
    {
        Site db = new Site();
        CommentsViewModel commenstVm = new
        {
            comments = db.GetComments(),
            comment = new Comment(),
            commentCategories = db.GetCommentCategories()
        };

        return View(commentsVm);
    }


    [HttpPost]
    public ActionResult AddNewComment(CommentsViewModel commentVm)
    {
        Site db = new Site();
        if (!ModelState.IsValid)
        {
            return View("Index", commentVm);
        }
        db.AddComment(commentVm.comment);

        return RedirectToAction("Index");
    }
}

Upvotes: 0

Views: 1598

Answers (1)

Dennis Rongo
Dennis Rongo

Reputation: 4611

Here's a basic View and the Controller that you can use as a starting point.

Model and ViewModel:

public class CommentsViewModel
{
    public IList<Comment> comments { get; set; }

    public CommentsViewModel()
    {
        comments = new List<Comment>();
    }
}

public class Comment
{
    [Required]
    public string commentData { get; set; }
    /** Omitted other properties for simplicity */
}

View:

@using (@Html.BeginForm("Index", "Comments"))
{
   @Html.TextBoxFor(t => t.comment.commentData)
   @Html.ValidationMessageFor(t=> t.comment.commentData, "", new {@class = "red"})
   <button name="button" value="addcomment">Add Comment</button>
}

@foreach (var t in Model.comments)
{
    <div>@t.commentData</div>
}

Controller:

public class CommentsController : Controller
{
    /** I'm using static to persist data for testing only. */
    private static CommentsViewModel _viewModel;

    public ActionResult Index()
    {
        _viewModel = new CommentsViewModel();
        return View(_viewModel);
    }

    [HttpPost]
    public ActionResult Index(Comment comment)
    {
        if (ModelState.IsValid)
        {
            _viewModel.comments.Add(
                new Comment() {commentData = comment.commentData});
            return View("Index", _viewModel);
        }

        return RedirectToAction("Index");
    }
}

Upvotes: 1

Related Questions