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

Html Form和 Ajax Form区别:

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

Step1:创建一个MVC项目

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

[html] view plaincopy
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@{
  2. ViewBag.Title = "Home Page";
  3. }
  4. <h2>@ViewBag.Message</h2>
  5. <p>
  6. @using(Html.BeginForm("TestHtmlRedirect", "Test",FormMethod.Post, null))
  7. {
  8. <input type="submit"value="Html PsBk Click" />
  9. }
  10. </p></span>

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

[java] view plaincopy
  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 plaincopy
  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. <h2>@ViewBag.Message</h2>
  6. <p>
  7. @using(Ajax.BeginForm("TestAjaxRedirect", "Test",FormMethod.Post, null))
  8. {
  9. <input type="submit"value="Ajax PsBk Click" />
  10. }
  11. </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
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">  <!--启用客户端验证,Start。。。-->
  2. <addkeyaddkey="ClientValidationEnabled" value="true"/>
  3. <!--支持JavaScript的执行-->
  4. <addkeyaddkey="UnobtrusiveJavaScriptEnabled" value="true"/></span>

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

[java] view plaincopy
  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 plaincopy
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">@{
  2. ViewBag.Title = "关于我们";
  3. }
  4. <h2>关于</h2>
  5. <p>
  6. 将内容放置在此处。
  7. </p></span>

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

[java] view plaincopy
  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">public ActionResult About() {
  2. return View();
  3. }</span>

(3)Global.asax

[java] view plaincopy
  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. namespaceComplaintManageSystem
  8. {
  9. // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
  10. // 请访问 http://go.microsoft.com/?LinkId=9394801
  11. public class MvcApplication :System.Web.HttpApplication
  12. {
  13. public static voidRegisterGlobalFilters(GlobalFilterCollection filters)
  14. {
  15. filters.Add(newHandleErrorAttribute());
  16. }
  17. public static voidRegisterRoutes(RouteCollection routes)
  18. {
  19. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  20. routes.MapRoute(
  21. "Default", // 路由名称
  22. "{controller}/{action}/{id}", // 带有参数的 URL
  23. new { controller ="Test", action = "TestHtmlView", id =UrlParameter.Optional } // 参数默认值
  24. );
  25. }
  26. protected void Application_Start()
  27. {
  28. AreaRegistration.RegisterAllAreas();
  29. RegisterGlobalFilters(GlobalFilters.Filters);
  30. RegisterRoutes(RouteTable.Routes);
  31. }
  32. }
  33. }
  34. </span>

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

  1

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

 2

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

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

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

Step8:定义一个实体 PersonnelModel

[java] view plaincopy
  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. public string UserName { get; set; }
  12. public string MailAdress { get; set; }
  13. }
  14. }</span>

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

HtmlViewModel.cshtml:

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

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

[java] view plaincopy
  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就可以很容易的完成一个异步的表单提交动作。

转载于:https://www.cnblogs.com/zjoch/p/4350072.html

Html.BeginForm() vs Ajax.BeginForm() in MVC3相关推荐

  1. 转:MVC3系列:~Html.BeginForm与Ajax.BeginForm

    Html.BeginForm与Ajax.BeginForm都是MVC架构中的表单元素,它们从字面上可以看到区别,即Html.BeginForm是普通的表单提交,而Ajax.BeginForm是支持异步 ...

  2. ajax.beginform onfailure,如何使用Ajax.BeginForm OnSuccess和OnFailure方法?

    我也寻找相同的答案,但看起来像Ajax.BeginForm()..的事件的都有详细的记载或需要更多的自我实验发现当这些onSuccess和onFailure事件被调用时.但是我得到了一个非常简单直接的 ...

  3. Ajax.BeginForm无法调用 ajaxOptions的js函数

    使用ajax.beginForm无法调用ajaxOptions的js函数的原因,一般都是缺少以下2个JS文件: 1,Install-Package jQuery –version 1.10.2 2,I ...

  4. data ajax begin,Ajax.BeginForm()知多少

    在ASP.NET MVC中,Ajax.BeginForm扮演着异步提交的重要角色.其中就有五个重载方法,可是在实际应用中,你未必使用的驾轻就熟,今天咱们就从主要的参数来一探究竟. javascript ...

  5. C#MVC Razor的Ajax.BeginForm里面的OnSuccess未执行(未成功跳转)

    C#MVC Razor的Ajax.BeginForm里面的OnSuccess未执行(未成功跳转),结合网上的说法,检查以下位置 1.引用Jquery,注意版本,网上说版本要低一点 <script ...

  6. asp.net core mvc 异步表单(Ajax.BeginForm)

    .net core中已经没有beginform扩展函数了. 通过Bower引入jquery-ajax-unobtrusive: <script src="~/lib/jquery-aj ...

  7. mvc4 html.beginform,MVC4 Html.BeginForm在Internet Explorer中提交按钮 9不工

    我已经写在ASP.NET MVC4 /剃刀的形式. 该表格后很完善在Firefox和Chrome,但由于某种原因在Internet Explorer 10和11,"提交"按钮没有反 ...

  8. MVC下HtmlHelper自带BeginForm表单提交与异步Ajax请求

    假如有一个数据表格UserInfo: public class UserInfo {public int Id { get; set; }public string Name { get; set; ...

  9. mvc3中正确处理ajax访问需要登录的页面

    mvc3中有Ajax.ActionLink和Ajax.BeginForm两个方法用来生成ajax的连接和ajax的表单提交. 但是当要访问的连接是一个需要登录的页面,显示时就不太友好了 我简单模拟了一 ...

最新文章

  1. 云计算安全:技术与应用
  2. 如何根据keras的fit后返回的history绘制loss acc曲线
  3. 开始接触QM(Quality Management)
  4. 最有影响力的自然语言处理NLP论文
  5. 用四种方法Python求出两个有序数组中的中位数
  6. R语言统计与绘图:正态、方差齐性、多重比较
  7. Vue-Router + Vuex 实现单页面应用
  8. Python 教你自动发微博,每日一句英语
  9. Web API——添加Swagger、SQL Server、日志记录、导出到Excel和Docker
  10. php 在模板中赋值数组变量,PHP自定义函数实现assign()数组分配到模板及extract()变量分配到模板功能示例...
  11. logback 配置详解(一)configuration and logger
  12. mysql数据库中如何创建角色_MySQL数据库如何创建用户呢?
  13. 二维码生成原理及解析代码
  14. 同频切换的事件_目前现网中,LTE同频切换主要是通过A5事件进行触发
  15. mysql怎么创建外表_PostgreSQL使用MySQL外表的步骤详解(mysql_fdw)
  16. 分享个免费的图文识别orc接口
  17. MYSQL学习笔记06:列属性[NULL,default,comment],主键,自增长,唯一键,数据库设计规范[范式(1NF,2NF,3NF),逆规范化],表关系[1V1,1VN,NVN]
  18. Java设计模式入门
  19. 分布式系统与计算机网络
  20. localhost:8080网址进入后不是Tomcat 而是phpwamp 为什么?怎么解决? 我想这个网址打开是Tomcat 求大神解疑。

热门文章

  1. python中的构造函数和构造函数和析构函数的作用
  2. centos6系列版本防火墙图形化设置
  3. Nginx 0.8.5版本access.log日志分析shell命令
  4. windows8中的数据上下文和简单的ListView
  5. eclipse自动补全的设置
  6. Smarty2至Smarty3升级指南
  7. 使用MEF构建可扩展的Silverlight应用
  8. 迈克尔·乔丹,无可复制的篮球之神!
  9. 一次诡异的数据库死锁问题排查过程 1
  10. 设计模式(一)简单工厂(创建型)(JavaPHP)