功能说明
基于 ajaxForm 插件进行构建,可以使表单通过ajax的方式进行提交,并扩展了以下功能:
更多信息请参见:
调用ajaxForm,自定义success和error方法
评论内容中有字符串:“error”,即模拟请求出错
Action代码:
[HttpPost] public ActionResult _CreateComment(PhotoCommentEditModel model) { if (!ModelState.IsValid) return View(model); PhotoComment comment = model.AsPhotoComment(); if (comment.Body.Contains("error"))//测试,当输入error的时候表示出错 { WebUtility.SetStatusCodeForError(Response); return View("_CreateComment", new PhotoCommentEditModel() { PhotoId = model.PhotoId }); } else { this.photoCommentService.Create(comment); return Json(new { comment.Id }); } }
View代码:
@using (Html.BeginAjaxForm("_CreateComment", "HtmlHelper", FormMethod.Post, new AjaxFormOptions().SetOnSuccessCallBack("success").SetOnErrorCallBack("error"))) { //... } <script type="text/javascript"> function error() { alert("error"); } function success() { $("#PhotoComments").load("@(Url.Action("_PhotoComments", new { photoId = 1 }))"); } </script>
调用ajaxForm,使用Target
Action代码:
[HttpPost] public ActionResult CreateCommentForList(PhotoCommentEditModel model) { if (!ModelState.IsValid) return View("_ListComments", model); PhotoComment comment = model.AsPhotoComment(); this.photoCommentService.Create(comment); return _ListComments(model.PhotoId); }
View代码:
@Html.Action("_PhotoComments", new { photoId = Model.PhotoId }) @using (Html.BeginAjaxForm("CreateCommentForList", "HtmlHelper", FormMethod.Post, new AjaxFormOptions { Target = "#ListComments", ReplaceTarget = true })) { //... }
在模式框中提交表单
因为出错时,需要更新模式框内容,要用到模式框实例,可以通过在模式框内容的<script type="text/dialog"> </script>来获取实例。
@using (Html.BeginAjaxForm("_CreateComment", "HtmlHelper", FormMethod.Post, new AjaxFormOptions().SetOnSuccessCallBack("success"))) { //... } <script type="text/dialog"> var dialog=this; this.title("发表新评论"); </script> <script type="text/javascript"> function error(response) { $("#CreateComment").html(response); } function success() { $("#PhotoComments").load("@(Url.Action("_PhotoComments", new { photoId = 1 }))"); } </script>
评论 (0)