C# 在同一页面上显示评论和发布表单以添加新评论
我正在C# 在同一页面上显示评论和发布表单以添加新评论,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我正在ASP.NET MVC中构建一个web应用程序。我有一个评论页面,其中的评论显示在从最新到最旧的列表中,并且在底部有一个表单,用户可以在其中发布新的评论。 除了在页面上显示最新评论外,还应突出显示表单条目 如果显示的数据和发布表单位于同一页面上,那么最好的方法是什么 没有ajax也能做到这一点吗 --代码摘录-- class CommentsViewModel { 公共IList注释{get;set;} 公共注释注释{get;set;} 公共选择列表注释类别{get;set;} } 课堂评
ASP.NET MVC
中构建一个web应用程序。我有一个评论页面,其中的评论显示在从最新到最旧的列表中,并且在底部有一个表单,用户可以在其中发布新的评论。
除了在页面上显示最新评论外,还应突出显示表单条目
如果显示的数据和发布表单位于同一页面上,那么最好的方法是什么
没有ajax也能做到这一点吗
--代码摘录--
class CommentsViewModel
{
公共IList注释{get;set;}
公共注释注释{get;set;}
公共选择列表注释类别{get;set;}
}
课堂评论
{
[必需]
公共字符串commentData{get;set;}
[必需]
public int?commentCategory{get;set;}
}
类注释:控制器
{
公共行动结果索引()
{
Site db=新站点();
CommentsViewModel commonstvm=new
{
comments=db.GetComments(),
注释=新注释(),
commentCategories=db.GetCommentCategories()
};
返回视图(SVM);
}
[HttpPost]
公共操作结果添加新成员(CommentsViewModel commentVm)
{
Site db=新站点();
如果(!ModelState.IsValid)
{
返回视图(“索引”,commentVm);
}
db.AddComment(commentVm.comment);
返回操作(“索引”);
}
}
这是一个基本的视图
和控制器
,您可以将其用作起点
模型和视图模型:
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");
}
}
它应该很简单。你的代码看起来像什么?您所需要做的就是呈现一个包含所有注释字段的空表单,然后在另一个区域中循环通过传递到
视图的模型
。您可以使用JavaScript突出显示最新的评论。我已经编辑了您的标题。请看“”,其中的共识是“不,他们不应该”。你所说的“处理页面的最佳方式”到底是什么意思?很抱歉@KodeKreachor。我已经更新了这个问题。@DennisRongo我已经添加了一些控制器和模型。
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");
}
}