如何在asp.net MVC中将表单提交到数据库中

时间:2014-07-13 03:03:54

标签: c# jquery asp.net asp.net-mvc asp.net-mvc-4

我正在asp.net MVC中建立一个评论系统。没什么好看的,但仍然高于我的技术水平。我正在使用partialview在页面上显示评论表单,并且需要已登录的用户能够发表评论并让部分视图重新加载他们提交的内容。

我目前的代码如下:

查看:

@using Microsoft.AspNet.Identity
@model DCH.Web.Models.CollaborativeProjectDetailsViewModel
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>
tinymce.init({ selector: '#commentBox',
    plugins: [
        ["advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker"],
        ["searchreplace wordcount visualblocks visualchars code insertdatetime media nonbreaking"],
        ["save table contextmenu directionality emoticons template paste"]
    ],
    statusbar: false,
    menubar: false
});
</script>
@{
var loggedInUser = User.Identity.GetUserName();
}
    <!--Comments-->

<div>
<h3>Comments</h3>
<p> You are logged in as: <span class="commentUser">@loggedInUser</span> 
@Html.ActionLink("(Log Out)", "LogOut", "Account")</p>
</div>
@using (Ajax.BeginForm("CommentForm", null, new AjaxOptions { HttpMethod = "POST",     InsertionMode = InsertionMode.Replace }, new { id = "CollaborativeCommentForm" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div>
    @Html.ValidationMessageFor(m => m.Content)
    @Html.TextAreaFor(m => m.Content, new {style = "max-width: 1000px; width = 1000px", @class = "form-control", rows = "10", id = "commentBox"})
</div>
<div class="pull-right comment-submit-top-pad">
    <input type="button" value="Cancel" class="btn btn-danger" />
    <input type="button" value="Submit" class="btn btn-primary" />
</div>

<!--End Comments-->

}

型号:

[Required]
    public int Id { get; set; }
    public string PostedBy { get; set; }
    public DateTime PostedOn { get; set; }
    [Required(ErrorMessage = "Please fill in a comment below")]
    [AllowHtml]
    public string Content { get; set; }

控制器:

[HttpPost]
    public ActionResult CommentForm(CollaborativeProjectDetailsViewModel model)
    {
        if (ModelState.IsValid)
        {
            Session["CollaborativeComments"] = model;

        }
        return PartialView("CollaborativeComments");
    }

现在我浏览了asp.net上的教程,但仍然坚持做什么。我知道我必须能够db.Comments.Add但不确定如何生成这样的代码。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我建议您前往http://www.entityframework.org/entity-framework-getting-started/进行演练,以便了解EF尝试做什么的基础知识。

完成后,您将知道上面要做什么。使用EF非常简单,但如果您质疑文章将如何向您展示。

祝你好运。 :)