ajax 添加评论

Index.cshtml @model IEnumerable<string> @section head { <script type="text/javascript" src="@Url.Content("../../scripts/ajaxdemo.js")"></script> } <h4>comments</h4> <ul id="comments"> @foreach (var comment in Model) { <li>@comment</li> } </ul> <form mothed="post" action="@Url.Action("AddComment")" id="commentForm"> @Html.TextArea("comment", new { rows = 5, cols = 50 }) <br /> <input id="Submit" type="submit" value="add commit" /> </form> $(document).ready(function () { $('#commentForm').submit(function (event) { event.preventDefault(); var data = $(this).serialize();//序列化内容 var url = $(this).attr('action'); $.post(url, data, function (response) { $('#comments').append(response); }); }); }); AddComment.cshtml 部分视图 <li>@ViewBag.Comment</li>   CustomAjaxController.cs public class CustomAjaxController : Controller { private static List<string> comments = new List<string>(); // GET: CustomAjax public ActionResult Index() { return View(comments); } [HttpPost] public ActionResult AddComment(string comment) { comments.Add(comment); if (Request.IsAjaxRequest()) { ViewBag.Comment = comment; return PartialView(); } else { return RedirectToAction("index"); } } }
posted @ 2017-03-05 00:00  PhilXu  阅读(189)  评论(0编辑  收藏  举报