0

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

最好的方法是什么,显示的数据和发布表单在同一页面上?

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

1 回答 1

1

这是一个基本ViewController,您可以将其用作起点。

模型和视图模型:

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");
    }
}
于 2013-02-02T00:26:45.223 回答