-1
我正在写博客。有了这个博客,我可以发送消息,人们可以对这些消息作出反应。为了达到这个目的,我制作了两个模型,消息和评论。由此,消息可以具有多个评论,因此它们具有一对多的关系。现在我正在尝试为消息添加新的评论,但我没有得到它的工作。向数据库添加新的相关对象
当我添加一条消息时,它从我的try catch语句中返回我的视图。
我已将其追踪到我尝试将值绑定到我的评论模型中的foreignkey messagesId的部分。 我正在做这件事,因为我想将我的评论分配给一条消息。
这里是我的模型
namespace Portfolio.Models
{
public class Messages
{
public int MessagesId { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Body { get; set; }
public DateTime WhenCreated { get; set; }
public virtual ICollection<Comments> Comments { get; set; }
public Messages()
{
WhenCreated = DateTime.Now;
}
}
}
namespace Portfolio.Models
{
public class Comments
{
public int CommentsId { get; set; }
public string Comments_body { get; set; }
public DateTime WhenCreated { get; set; }
public int ComToMes { get; set; }
public virtual Messages Messages { get; set; }
public Comments()
{
WhenCreated = DateTime.Now;
}
}
}
这里是我的控制器
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateComments(FormCollection formValues)
{
try
{
Comments comment = new Comments();
comment.Comments_body = formValues["editor"];
var currentMessage
=_context.messages.Find(Int32.Parse(formValues["IdName"]));
comment.Messages.MessagesId = currentMessage.MessagesId;
_context.comments.Add(comment);
_context.SaveChanges();
}
catch
{
return View();
}
return RedirectToAction("Blog");
}
这里是我的看法
@*The form to post comments*@
@using (Html.BeginForm("CreateComments", "Messages"))
{
<div class="form-group">
<label>Comment</label>
@Html.TextArea("editor", htmlAttributes: new { name = "editor1",
id = "editor", rows = "10", cols = "180" }
@Html.Hidden("IdName",messages.MessagesId)
</div>
<button type="submit" class="btn btn-primary" id="PostButton">Post
Comment</button>
}
您的“评论”模型需要“消息”的导航属性 - 例如, 'public int MessageId {get;组; }'。但你真的需要去MVC网站并通过教程来学习基础知识。 –
我可以给你的一个非常好的提示是为你的实体名称使用单数。 '消息'和'评论'。它确实有助于可读性(特别是一目了然)。 – Flater
thnx即时即将改变,马上@Flater – ruinerwarrior