爱上MVC3系列~当Ajax.Beform不能满足我们的要求时...

mvc架构中提供了Html.BeginForm与Ajax.BeginForm,主要实现同步提交表单与异步提交表单,对于同步提交与传统的方式没有区别,而异步表单MVC自己进行了封装(可以看我的文章了解两种方式的表单提交),使我们很轻松的完成异步提交,而如果你的视图比较复杂,使用AJAX.BeginForm可能就显得不可供了,有时需要修改异步回调的细节,有时需要返回特定的消息,而这时你必须要手动写异步表单了,今天主要来说一下JQ实现的异步表单提交。效果:

JS提交表单代码:

 1 <script type="text/javascript">

 2     function submitForm() {

 3         $.ajax({

 4             type: 'POST',

 5             url: '@Url.Action("AJAXReview", "Common")',

 6             data: $("#form1").serialize(),

 7             success: function (data) {

 8                 if (data.res)

 9                     alert("提交成功");

10                 else

11                     alert("提交失败,失败信息为:" + data.info);

12             }

13         })

14     }

15 </script>

View:

 1 @using (Html.BeginForm("Review", "Common", FormMethod.Post, new

 2 {

 3     id = "form1"

 4 }))

 5 {

 6     <fieldset>

 7         <legend>评论 </legend>

 8         <ul>@Html.ValidationSummary(true)

 9             @Html.HiddenFor(i => i.ObjID)

10             @Html.HiddenFor(i => i.ObjType)

11             <li></li>

12             <li>标题:@Html.TextBoxFor(i => i.Title)</li>

13             <li>@Html.ValidationMessageFor(i => i.Title)</li>

14             <li>内容:@Html.TextAreaFor(i => i.Content)</li>

15             <li>@Html.ValidationMessageFor(i => i.Content)</li>

16         </ul>

17     </fieldset>

18     <input type="button" onclick="submitForm()" value="提交" />

19 }

Model:

 1   /// <summary>

 2   /// 评论对象

 3   /// </summary>

 4   public class Review

 5   {

 6     public long ID { get; set; }

 7     public int ObjType { get; set; }

 8     public long ObjID { get; set; }

 9     [Required]

10     public string Title { get; set; }

11     [Required]

12     public string Content { get; set; }

13     [Required]

14     public DateTime CreateDate { get; set; }

15   }

Controller:

 1    /// <summary>

 2     /// 异步评论视图

 3     /// </summary>

 4     /// <param name="objID"></param>

 5     /// <param name="objType"></param>

 6     /// <returns></returns>

 7     public ActionResult AJAXReview(int? objID, int? objType)

 8     {

 9       return View(new Review

10       {

11         ObjID = objID ?? 0,

12         ObjType = objType ?? 1,

13         Content = "",

14         Title = "",

15       });

16     }

17     [HttpPost]

18     public JsonResult AJAXReview(Review entity)

19     {

20       JsonResult js = new JsonResult();

21       js.Data = new { res = true };

22       if (ModelState.IsValid)

23       {

24         //相关逻辑

25       }

26       else

27       {

28         js.Data = new { res = false, info = "请认真填写表单!" };

29       }

30       return js;

31     }

恩,这样可以实现的效果如图:

您可以对页面提示的效果进行改进,这对于开发者来说是容易的。

你可能感兴趣的:(Ajax)