我的视图模型
public class PostViewModel
{
public Post Post { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
在我的剃刀视图中,我正在尝试为我的评论获取数据
@using (Html.BeginForm("Comment", "Post"))
{
<div class="form-group">
@Html.LabelFor(m => m.Comments.Data);
@Html.TextAreaFor(m => m.Comments.Data, new { @class = "form-control" })
</div>
@Html.HiddenFor(m => m.Comments.Id)
<button type="submit" class="btn btn-primary"> Comment </button>
}
但我收到错误
然后我尝试了以下语法
@using (Html.BeginForm("Comment", "Post"))
{
@foreach(var comment in Model.Comments)
{
<div class="form-group">
@Html.LabelFor(comment.Data);
@Html.TextAreaFor(comment.Data, new { @class = "form-control" })
</div>
@Html.HiddenFor(comment.Id)
<button type="submit" class="btn btn-primary"> Comment </button>
}
}
但我仍然收到错误
实际上我在做一个博客项目
所以,我希望在详细信息页面中有发布、所有旧评论和新评论按钮
Ehsan Sajjad 让我明白我们可以这样写 lambda 表达式
@Html.LabelFor(x=> comment.Data)
后来我解决了我的问题,其实我的做法是很错误的
为了解决我的问题,我在 ViewModel 中添加了另一个组件 NewComment
public class PostViewModel
{
public Post Post { get; set; }
public IEnumerable<Comment> Comments { get; set; }
public Comment NewComment { get; set; } // this is new addition
}
然后我的新评论区域在剃刀语法中如下所示
@using (Html.BeginForm("Comment", "Post", Model.Post))
{
var comment = Model.NewComment;
<div class="form-group">
@Html.LabelFor(m => comment.Data);
@Html.TextAreaFor(m => comment.Data, new { @class = "form-control" })
</div>
@Html.HiddenFor(m => comment.Id)
<button type="submit" class="btn btn-primary"> Comment </button>
}
我正在做一个项目,在详细信息视图中
首先,出现了一个帖子
其次,是评论
第三,它的新评论部分
它的详细信息页面的完整代码
@model SimpleBlog.Models.PostViewModel
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@*Post Section*@
<div class="jumbotron">
<h1> @Model.Post.Title </h1>
<p class="lead"> @Model.Post.PostedBy </p>
<p> @Model.Post.PostDate.ToString("d MMM yyyy") </p>
</div>
<br />
<div class="jumbotron">
<p class="lead"> @Model.Post.Body </p>
</div>
@* Old comments section *@
@foreach (var comment in Model.Comments)
{
<h4> @comment.CommentBy </h4>
<h4> @comment.CommentDate.ToString("d MMM yyyy") </h4>
<h4> @comment.Data </h4>
<br />
<br />
}
@* New Comment section *@
@using (Html.BeginForm("Comment", "Post", Model.Post))
{
var comment = Model.NewComment;
<div class="form-group">
@Html.LabelFor(m => comment.Data);
@Html.TextAreaFor(m => comment.Data, new { @class = "form-control" })
</div>
@Html.HiddenFor(m => comment.Id)
<button type="submit" class="btn btn-primary"> Comment </button>
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句