300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Html.BeginForm() vs Ajax.BeginForm() in MVC3

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

时间:2021-09-21 03:49:08

相关推荐

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

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

HtmlForm和Ajax Form区别:

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

Step1:创建一个MVC项目

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

[html]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">@{ViewBag.Title="HomePage";}<h2>@ViewBag.Message</h2><p>@using(Html.BeginForm("TestHtmlRedirect","Test",FormMethod.Post,null)){<inputtype="submit"value="HtmlPsBkClick"/>}</p></span>

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

[java]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">//ThissectionofcodeisforTestHtmlView.cshtmlpublicActionResultTestHtmlView(){ViewBag.Message="HtmlForm——ThisisaHTMLform";returnView();}[HttpPost]publicActionResultTestHtmlRedirect(){returnRedirectToAction("TestAjaxView","Test",null);}//EndofthesectionofcodeforTestHtmlView.cshtml</span>

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

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

[html]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">@{ViewBag.Title="TestPage";}<scriptsrcscriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script><h2>@ViewBag.Message</h2><p>@using(Ajax.BeginForm("TestAjaxRedirect","Test",FormMethod.Post,null)){<inputtype="submit"value="AjaxPsBkClick"/>}</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 plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;"><!--启用客户端验证,Start。。。--><addkeyaddkey="ClientValidationEnabled"value="true"/><!--支持JavaScript的执行--><addkeyaddkey="UnobtrusiveJavaScriptEnabled"value="true"/></span>

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

[java]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">//ThissectionofcodeisforTestAjaxView.cshtmlpublicActionResultTestAjaxView(){ViewBag.Message="AjaxForm——ThisisaAJAXform";returnView();}[HttpPost]publicActionResultTestAjaxRedirect(){returnRedirectToAction("About","Test",null);}//EndofSectionofcodeforTestAjaxView.cshtml</span>

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

(附录:

(1)About.cshtml:

[html]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">@{ViewBag.Title="关于我们";}<h2>关于</h2><p>将内容放置在此处。</p></span>

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

[java]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">publicActionResultAbout(){returnView();}</span>

(3)Global.asax

[java]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;usingSystem.Web.Routing;namespaceComplaintManageSystem{//注意:有关启用IIS6或IIS7经典模式的说明,//请访问/?LinkId=9394801publicclassMvcApplication:System.Web.HttpApplication{publicstaticvoidRegisterGlobalFilters(GlobalFilterCollectionfilters){filters.Add(newHandleErrorAttribute());}publicstaticvoidRegisterRoutes(RouteCollectionroutes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute("Default",//路由名称"{controller}/{action}/{id}",//带有参数的URLnew{controller="Test",action="TestHtmlView",id=UrlParameter.Optional}//参数默认值);}protectedvoidApplication_Start(){AreaRegistration.RegisterAllAreas();RegisterGlobalFilters(GlobalFilters.Filters);RegisterRoutes(RouteTable.Routes);}}}</span>

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

1

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

2

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

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

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

Step8:定义一个实体PersonnelModel

[java]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Reflection;usingModel.Adapter;namespaceModel.Entity{publicclassPersonnelModel{publicstringUserName{get;set;}publicstringMailAdress{get;set;}}}</span>

Step9:再分别定义Html和Ajax视图

HtmlViewModel.cshtml:

[html]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">@modelHtmlVsAjaxBeginForm.Models.PersonnelModel@{ViewBag.Title="HtmlViewModel";}<h2>HtmlViewModel</h2>@using(Html.BeginForm("HtmlViewModel","Home",null)){@Html.ValidationSummary(true)<fieldset><legend>PersonnelModel</legend><divclassdivclass="editor-label">@Html.LabelFor(model=>model.UserName)</div><divclassdivclass="editor-field">@Html.EditorFor(model=>model.UserName)@Html.ValidationMessageFor(model=>model.UserName)</div><divclassdivclass="editor-label">@Html.LabelFor(model=>model.MailAdress)</div><divclassdivclass="editor-field">@Html.EditorFor(model=>model.MailAdress)@Html.ValidationMessageFor(model=>model.MailAdress)</div></fieldset><p><inputtype="submit"value="HtmlFormAction"/></p>}</span>

AjaxViewModel.cshtml:

[html]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">@modelModel.Entity.PersonnelModel@{ViewBag.Title="AjaxViewModel";}<scriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script><h2>AjaxViewModel</h2>@using(Ajax.BeginForm("AjaxViewModel","Test",newAjaxOptions{UpdateTargetId="result"})){@Html.ValidationSummary(true)<fieldset><legend>PersonnelModel</legend><divid="result"></div><divclass="editor-label">@Html.LabelFor(model=>model.UserName)</div><divclass="editor-field">@Html.EditorFor(model=>model.UserName)@Html.ValidationMessageFor(model=>model.UserName)</div><divclass="editor-label">@Html.LabelFor(model=>model.MailAdress)</div><divclass="editor-field">@Html.EditorFor(model=>model.MailAdress)@Html.ValidationMessageFor(model=>model.MailAdress)</div></fieldset><p><inputtype="submit"value="AjaxFormAction"/></p>}</span>

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

[java]view plaincopy <spanstyle="font-family:KaiTi_GB2312;font-size:18px;">//HTMLFormMethod//Purpose:Willreturnthebelowcontent,onceafterthemethodtriggered.[HttpPost]publicActionResultHtmlViewModel(PersonnelModelPmodel){returnContent("Hi"+Pmodel.UserName+",Thanksforthedetails,amailwillbesentto"+Pmodel.MailAdress+"withallthelogindetails.","text/html");}//AJAXFormMethod//Purpose:Willreturnthebelowcontent,onceafterthemethodtriggered.[HttpPost]publicActionResultAjaxViewModel(PersonnelModelPmodel){returnContent("Hi"+Pmodel.UserName+",Thanksforthedetails,amailwillbesentto"+Pmodel.MailAdress+"withallthelogindetails.","text/html");}</span>

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

HtmlViewModel.cshtml加载:

文本框中输入数据:

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

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

AjaxViewModel.cshtml加载:

文本框中输入数据:

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

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

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

总结:

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

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。