在同一页面上显示评论和发布表单以添加新评论

时间:2013-02-01 18:27:09

标签: c# asp.net asp.net-mvc

我正在ASP.NET MVC中构建一个Web应用程序。我有一个评论页面,其中评论显示在最新到最旧的列表中,并且底部还有一个表单,用户可以在其中发布新评论。 除了显示最新评论的页面外,还应突出显示表单条目。

最好的方法是什么,显示的数据和帖子表格在同一页面上?

是否可以在没有ajax的情况下执行此操作?

- 代码提取 -

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");
    }
}

1 个答案:

答案 0 :(得分:1)

以下是您可以用作起点的基本ViewController

模型和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 */
}

查看:

@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>
}

<强>控制器:

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");
    }
}