爱上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 }
恩,这样可以实现的效果如图:
您可以对页面提示的效果进行改进,这对于开发者来说是容易的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2011-12-04 MVC中对controller的抽象