ASP.NET MVC 入门教程(四)发表评论

耗尽温柔 提交于 2020-03-25 13:02:16

3 月,跳不动了?>>>

ASP.NET MVC 入门教程(四)

本部分主要实现评论内容的发表

一、在文章内容页上创建发表评论表单

<!--发表评论-->
<form id="commentform" action="/Comment/Create" method="post">
    <input type="hidden" name="articleId" value="@Model.Id" />
    <div class="form-group">
        <label for="content">评论内容</label>
        <input type="text" class="form-control" id="content" name="content" placeholder="请输入评论内容" />
    </div>
    <button class="btn btn-default" id="btn">确定</button>
</form>

@section scripts{
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script>
        $(function () {
            $('#btn').on('click', function () {
                if($('#content').val()==""){
                    alert("请写下你的评论");
                    return false;
                };
            })
        });
    </script>
   
}

1.Js部分的代码主要用来验证,评论内容部分是否为空

2.<input type="hidden" name="articleId" value="@Model.Id" />

该隐藏的文本框,主要用于将文章的ID传递给评论,因为评论表中的ArticleId就是文章的Id值。

二、在Comment控制器里修改Create方法

1.删除基架生成的以下Create方法

在控制器中,基架生成了两个Create方法,下面这个Create方法是用来访问发表评论视图的,但在本实例中,评论表单是在文章内容页中呈现的,因此,并没有独立的一个视图页来呈现表单,所以该方法并不需要,删除即可。

// GET: Comment/Create
public ActionResult Create()
{
    return View();
}

2.修改以下的Create方法,代码如下

// POST: Comment/Create
        [HttpPost]
        public ActionResult Create(tb_comment comment)
        {
            if (ModelState.IsValid)
            {
                comment.CreateDate = DateTime.Now;
                db.tb_comment.Add(comment);
                db.SaveChanges();
                return RedirectToAction("Details", "Article", new { id = comment.ArticleId });
            }
            return View();
        }

该方法的[HttpPost]只接收post方式进行的提交。

三、测试评论的发表

1.执行,打开浏览器

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!