我有一个类名称注释如下
public class Comment
{
public int Id { get; set; }
public string Name { get; set; }
public string Coment { get; set; }
}
我想要做什么,我想显示评论列表和一个在同一 View (索引)上添加评论的表单,这就是我所做的,到目前为止,但我无法获取 提示
,这是我的索引 View
@model IEnumerable<GuestbookEntryApp.Models.Comment>
<h2>Index</h2>
<div id="CommentList">
<table>
<tr>
<th>Name</th>
<th>Comments</th>
</tr>
@foreach (var obj in Model)
{
<tr>
<td>@obj.Name</td>
<td>@obj.Coment</td>
</tr>
}
</table>
</div>
<br />
<div id="commentBox">
@Html.Partial("~/Views/Comments/_AddComment.cshtml", new ViewDataDictionary { Model = new GuestbookEntryApp.Models.Comment() })
</div>
但在这里我无法得到提示@Html.LabelFor(x => x.Name)
这是我的 Controller
public class CommentsController : Controller
{
GuestbookContext db = new GuestbookContext(); // my DbContxt Class
public ActionResult Index()
{
IList<Comment> _comment = db.Comments.ToList();
return View(_comment);
}
public PartialViewResult AddComment()
{
return PartialView("_AddComment");
}
public PartialViewResult AddComment(Comment _comment)
{
db.Comments.Add(_comment);
db.SaveChanges();
return RedirectToAction("Index");
}
}
有没有其他方法可以做到这一点。 我想要这样
最佳答案
使用现有评论和新评论的属性创建 View 模型
public class CommentVM
{
public IEnumerable<Comment> ExistingComments { get; set; }
public Comment NewComment { get; set; }
}
查看
@model YourAssembly.CommentVM
....
@foreach (var obj in Model.ExistingComments)
{
...
}
@using (Ajax.BeginForm("AddComment", .....}))
{
@Html.LabelFor(x => x.NewComment.Name)
....
并调整 Controller 以添加Bind.Prefix
属性
public ActionResult AddComment([Bind(Prefix="NewComment")]Comment _comment)
{
....
关于c# - 在 MVC 中的同一 View 上显示列表并提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25988821/