Html.BeginForm() vs Ajax.BeginForm() in MVC3

我们知道,BeginForm()方法能创建一个Form标签,因此可以结合表单级的方法,在这个页面中。我一直在考虑Html.BeginForm()方法和Ajax.BeginForm()方法在MVC3中有什么不同。读了很多博客,很多人都强调了一件事:Ajax FormForm被提交是使用了JavaScript异步提交的。

 

Html Form Ajax Form区别:

一,我做了一个简单的Demo来示范:

Step1:创建一个MVC项目

Step2:创建一个视图名为TestHtmlView.cshtml,此视图的Form表单使用Html.BeginForm()创建。此例子的操作是:当提交此表单时进行重定向;

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4.    
  5. <h2>@ViewBag.Message</h2>  
  6. <p>  
  7.     @using(Html.BeginForm("TestHtmlRedirect", "Test",FormMethod.Post, null))  
  8.     {  
  9.         <input type="submit"value="Html PsBk Click" />  
  10.     }  
  11. </p></span>  

 

 

Step3:定义两个action方法,一个用于返回创建的视图,一个用于响应表单提交;

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;"> //This section of code is forTestHtmlView.cshtml  
  2.         public ActionResult TestHtmlView()  
  3.         {  
  4.             ViewBag.Message = "HtmlForm——This is a HTML form";  
  5.             return View();  
  6.         }  
  7.         [HttpPost]  
  8.         public ActionResult TestHtmlRedirect()  
  9.         {  
  10.             returnRedirectToAction("TestAjaxView", "Test", null);  
  11.         }  
  12.         //End of the section of code forTestHtmlView.cshtml</span>  

 

 

看一下TestHtmlRedirect()方法的实现体,我们想从该视图重定向到另一个视图TestAjaxView.cshtml

 

Step4:创建一个视图名为AjaxHtmlView.cshtml,此视图的Form表单使用Ajax.BeginForm()创建。

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@{  
  2.     ViewBag.Title = "Test Page";  
  3. }  
  4. <scriptsrcscriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>  
  5.    
  6. <h2>@ViewBag.Message</h2>  
  7.    
  8. <p>  
  9.     @using(Ajax.BeginForm("TestAjaxRedirect", "Test",FormMethod.Post, null))  
  10.     {  
  11.         <input type="submit"value="Ajax PsBk Click" />    
  12.     }  
  13. </p></span>  

 

 

Step5:如果想让此Ajax Form正确工作,能达到预期,那么还需要在AjaxHtmlView.cshtml中添加此JS文件引用

<scriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>

 

还要确保在Web.Config文件中支持JS的执行,需要此配置文件中添加如下标签:

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">  <!--启用客户端验证,Start。。。-->  
  2.     <addkeyaddkey="ClientValidationEnabled" value="true"/>  
  3.   
  4.     <!--支持JavaScript的执行-->  
  5.     <addkeyaddkey="UnobtrusiveJavaScriptEnabled" value="true"/></span>  

 

Step6定义两个action方法,一个用于返回创建的视图,一个用于响应表单提交;

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">//This section ofcode is for TestAjaxView.cshtml  
  2.         public ActionResult TestAjaxView()  
  3.         {  
  4.             ViewBag.Message = "AjaxForm——This is a AJAX form";  
  5.             return View();  
  6.         }  
  7.         [HttpPost]  
  8.         public ActionResult TestAjaxRedirect()  
  9.         {  
  10.             returnRedirectToAction("About", "Test", null);  
  11.         }  
  12.         //End of Section of code forTestAjaxView.cshtml</span>  

 

 

看一下TestAjaxRedirect()方法的实现体,我们想从该视图重定向到另一个视图About.cshtml

(附录:

(1)About.cshtml:

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@{  
  2.     ViewBag.Title = "关于我们";  
  3. }  
  4.    
  5. <h2>关于</h2>  
  6. <p>  
  7.      将内容放置在此处。  
  8. </p></span>  

 

 

(2)Test控制器中添加About方法:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">public ActionResult About() {  
  2.             return View();  
  3.         }</span>  

 

 

(3)Global.asax

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">using System;  
  2. usingSystem.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. usingSystem.Web.Mvc;  
  6. usingSystem.Web.Routing;  
  7.    
  8. namespaceComplaintManageSystem  
  9. {  
  10.     // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,  
  11.     // 请访问 http://go.microsoft.com/?LinkId=9394801  
  12.    
  13.     public class MvcApplication :System.Web.HttpApplication  
  14.     {  
  15.         public static voidRegisterGlobalFilters(GlobalFilterCollection filters)  
  16.         {  
  17.             filters.Add(newHandleErrorAttribute());  
  18.         }  
  19.    
  20.         public static voidRegisterRoutes(RouteCollection routes)  
  21.         {  
  22.            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  23.    
  24.             routes.MapRoute(  
  25.                 "Default", // 路由名称  
  26.                "{controller}/{action}/{id}", // 带有参数的 URL  
  27.                 new { controller ="Test", action = "TestHtmlView", id =UrlParameter.Optional } // 参数默认值  
  28.             );  
  29.    
  30.         }  
  31.    
  32.         protected void Application_Start()  
  33.         {  
  34.            AreaRegistration.RegisterAllAreas();  
  35.    
  36.            RegisterGlobalFilters(GlobalFilters.Filters);  
  37.             RegisterRoutes(RouteTable.Routes);  
  38.         }  
  39.     }  
  40. }  
  41. </span>  

 

Step7:让我们开始执行程序,观察执行结果,如下图1

                                         1

当我点击图1中“Html PsBk Click”按钮时,TestHtmlRedirect()方法被调用,并且视图重定向到TestAjaxView.cshtml,如下图:

                                         2

 

现在,考虑一件事,当我点击图2"Ajax PsBk Click"按钮时,是否会发生同样的事,视图会重定向到About.cshtml?点击后,发现这件事并没有发生。

点击按钮后,TestAjaxRedirect()方法被调用,重定向语句段执行,但是视图并没有重定向。原因是:表单的提交使用了JavaScript的异步提交。正如我们看到的,操作的执行是异步的,Ajaxforms是适用于多种情况的,比如你需要修改或保存时是异步操作,但是不能重定向到其他表单。

 

二,下面,我们再做一个Demo,让我们测试一下HtmlformsAjax forms在执行修改操作时会有何不同。

Step8:定义一个实体 PersonnelModel

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">using System;  
  2. usingSystem.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. usingSystem.Reflection;  
  6. using Model.Adapter;  
  7. namespaceModel.Entity  
  8. {  
  9.     public class PersonnelModel  
  10.     {  
  11.    
  12.         public string UserName { get; set; }  
  13.          
  14.         public string MailAdress { get; set; }  
  15.    
  16.     }  
  17. }</span>  

 

Step9:再分别定义HtmlAjax视图

HtmlViewModel.cshtml:

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@modelHtmlVsAjaxBeginForm.Models.PersonnelModel  
  2. @{  
  3.     ViewBag.Title ="HtmlViewModel";  
  4. }  
  5. <h2>HtmlViewModel</h2>  
  6. @using (Html.BeginForm("HtmlViewModel","Home",null))      
  7. {  
  8.    @Html.ValidationSummary(true)  
  9. <fieldset>  
  10.    <legend>PersonnelModel</legend>      
  11.     <divclassdivclass="editor-label">  
  12.             @Html.LabelFor(model =>model.UserName)  
  13.         </div>  
  14.         <divclassdivclass="editor-field">  
  15.             @Html.EditorFor(model =>model.UserName)  
  16.            @Html.ValidationMessageFor(model => model.UserName)  
  17.         </div>      
  18.     <divclassdivclass="editor-label">  
  19.             @Html.LabelFor(model =>model.MailAdress)  
  20.         </div>  
  21.         <divclassdivclass="editor-field">  
  22.             @Html.EditorFor(model =>model.MailAdress)  
  23.            @Html.ValidationMessageFor(model => model.MailAdress)  
  24.        </div>  
  25. </fieldset>  
  26. <p>  
  27.     <input type="submit"value="Html Form Action" />  
  28. </p>  
  29. }</span>  

 

 

AjaxViewModel.cshtml:

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@model Model.Entity.PersonnelModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "AjaxViewModel";  
  5. }  
  6. <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>  
  7.   
  8. <h2>AjaxViewModel</h2>  
  9. @using (Ajax.BeginForm("AjaxViewModel", "Test", new AjaxOptions { UpdateTargetId = "result" }))      
  10. {  
  11.     @Html.ValidationSummary(true)  
  12. <fieldset>  
  13.     <legend>PersonnelModel</legend>  
  14.   
  15.     <div id="result"></div>  
  16.     <div class="editor-label">  
  17.             @Html.LabelFor(model => model.UserName)  
  18.         </div>  
  19.         <div class="editor-field">  
  20.             @Html.EditorFor(model => model.UserName)  
  21.             @Html.ValidationMessageFor(model => model.UserName)  
  22.         </div>  
  23.       
  24.     <div class="editor-label">  
  25.             @Html.LabelFor(model => model.MailAdress)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.MailAdress)  
  29.             @Html.ValidationMessageFor(model => model.MailAdress)  
  30.         </div>  
  31. </fieldset>  
  32. <p>  
  33.     <input type="submit" value="Ajax Form Action" />  
  34. </p>  
  35. }</span>  

 

Step10:定义两个action方法,目的均为返回数据内容,显示在各自视图中

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">//HTML Form Method  
  2.         //Purpose: Will return the belowcontent, once after the method triggered.  
  3.         [HttpPost]  
  4.         public ActionResultHtmlViewModel(PersonnelModel Pmodel)  
  5.         {  
  6.             return Content("Hi" + Pmodel.UserName + ", Thanks for the details, a mail will be sentto " + Pmodel.MailAdress + " with all the login details.","text/html");  
  7.         }  
  8.         //AJAX Form Method  
  9.         //Purpose: Will return the belowcontent, once after the method triggered.  
  10.         [HttpPost]  
  11.         public ActionResultAjaxViewModel(PersonnelModel Pmodel)  
  12.         {  
  13.             return Content("Hi" + Pmodel.UserName + ", Thanks for the details, a mail will be sentto " + Pmodel.MailAdress + " with all the login details.","text/html");  
  14.         }</span>  

 

Step11:现在分别运行这两个视图,点击各自按钮,观察执行效果:

HtmlViewModel.cshtml加载:

 

文本框中输入数据:

 

点击“Html Form Action”按钮后,运行效果:

弹出了新页面,将返回的数据显示

 

AjaxViewModel.cshtml加载:

 

文本框中输入数据:

 

点击“Ajax Form Action”按钮后,运行效果:

页面无刷新,将返回的数据显示在原页面

 

 

注:当然在Html forms中也可以产生如上Ajaxfroms中的效果,例如:js代码,使用Ajax请求函数)

总结:

       Html.BeginForm与Ajax.BeginForm都是MVC架构中的表单元素;

      区别:Html.BeginForm是普通的表单提交,而Ajax.BeginForm是支持异步的表单提交;

     Ajax.BeginForm()优点:不用再自己去用JQ代码了,直接用MVC自代的Ajax.BeginForm就可以很容易的完成一个异步的表单提交动作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值