ASP.NET MVC 入門教程(四)html
本部分主要實現評論內容的發表jquery
1、在文章內容頁上建立發表評論表單瀏覽器
<!--發表評論--> <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部分的代碼主要用來驗證,評論內容部分是否爲空post
2.<input type="hidden" name="articleId" value="@Model.Id" />測試
該隱藏的文本框,主要用於將文章的ID傳遞給評論,由於評論表中的ArticleId就是文章的Id值。code
2、在Comment控制器裏修改Create方法orm
1.刪除基架生成的如下Create方法htm
在控制器中,基架生成了兩個Create方法,下面這個Create方法是用來訪問發表評論視圖的,但在本實例中,評論表單是在文章內容頁中呈現的,所以,並無獨立的一個視圖頁來呈現表單,因此該方法並不須要,刪除便可。教程
// GET: Comment/Create public ActionResult Create() { return View(); }
2.修改如下的Create方法,代碼以下ip
// 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方式進行的提交。
3、測試評論的發表
1.執行,打開瀏覽器