以下是我的操作和我的PostIndexViewModel:
public ActionResult Comment(PostIndexViewModel model, FormalBlog Post)
{
var userName = User.Identity.Name;
var author = db.Users.SingleOrDefault(x => x.UserName == userName);
Comment newPost = new Comment();
newPost.Author = author;
newPost.Text = model.Text;
newPost.Post = model.Post;
db.Comments.Add(newPost);
db.SaveChanges();
return RedirectToAction("ShowBlogs", "Blog");
}
}
public class PostIndexViewModel
{
public string Id { get; set; }
public ICollection<FormalBlog> FormalBlogs { get; set; }
public FormalBlog NewFormalBlog { get; set; } = new FormalBlog();
public Category NewCategory { get; set; } = new Category();
public ICollection<Category> Categories { get; set; }
public List<SelectListItem> SelectedCategories { get; set; }
public int[] CategoryIds { get; set; }
public Category CategoryN { get; set; }
public ICollection<Meeting> Meetings { get; set; } //testrad
// public int Id { get; set; }
public string Text { get; set; }
public ApplicationUser Author { get; set; }
public Comment NewComment { get; set; }
public FormalBlog Post { get; set; }
}
以下是我的观点代码:
@model XP_Scrum_Grupp2.Controllers.PostIndexViewModel
@using (Html.BeginForm("Comment", "Blog", new { formal = Model }, FormMethod.Post, new { id = Model.Id }))
{
<div class="comment-form-container">
<form class="comment-form" data-action="@Url.Action("Comment", "Blog")">
@Html.HiddenFor(m => m.Id)
<div>@Html.DisplayFor(m => m.Author)</div>
<div>
<div>@Html.LabelFor(m => m.Text)</div>
@Html.TextAreaFor(m => m.Text, new { Class = "comment-text", rows = "3", cols = "50" })
</div>
<div class="comment-result" style="display: none;">
<span class="comment-result-text">An error occurred</span>
</div>
<div>
<button type="submit" class="comment-form-submit">Submit comment</button>
</div>
</form>
</div>
}
答案 0 :(得分:0)
您没有将任何数据发布为model.NewComment.Text
,因此NewComment
对象为null
时会发生错误。
@Html.TextAreaFor(m => m.Text, new { Class = "comment-text", rows = "3", cols = "50" })
所以,试着改变它;
newPost.Text = model.NewComment.Text;
到
newPost.Text = model.Text;
答案 1 :(得分:0)
您的观点未向model.NewComment.Text
分配任何值。因此,当您访问model.NewComment
时,它将抛出Null引用异常,因为model.Text
为空。
您将新文本分配给模型的Test属性。因此,您应该使用model.NewComment.Text
代替public ActionResult Comment(PostIndexViewModel model)
{
var userName = User.Identity.Name;
var author = db.Users.SingleOrDefault(x => x.UserName == userName);
Comment newPost = new Comment();
newPost.Author = author;
newPost.Text = model.Text;
newPost.Post = model.Post;
db.Comments.Add(newPost);
db.SaveChanges();
return RedirectToAction("ShowBlogs", "Blog");
}
{{1}}