1:新建-->项目-->Web-->ASP.NET MVC 4 Web 应用程序。命名为:Mvc4MicrosoftAjaxDemo
2:新建控制器:在Controllers文件夹上 右键-->添加-->控制器,命名为:HomeController (HomeController .cs)
3:在控制器HomeController中新增Action: GetDate()
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Threading;5 usingSystem.Web;6 usingSystem.Web.Mvc;7
8 namespaceMvc4MicrosoftAjaxDemo.Controllers9 {10 public classHomeController : Controller11 {12 //
13 //GET: /Home/
14
15 publicActionResult Index()16 {17 returnView();18 }19
20 publicActionResult GetDate()21 {22 //休眠1秒钟,监控前台动作
23 Thread.Sleep(1000);24 returnContent(DateTime.Now.ToString());25 }26 }27 }
HomeController.cs
4:新建视图:在HomeController Action:Index上 右键-->添加视图 命名:Index(默认和Action名称一致) (Index.cshtml)
5:在视图Index中添加以下代码,使用 微软提供的Ajax请求脚本,如下所示:
5.1:添加 jquery-1.8.2.min.js 和 jquery.unobtrusive-ajax.min.js的引用
1 @{2 Layout = null;3 }4
5
6
7
8
9
10
Index11
12
13
14
15
16
MVC 4 Microsoft Ajax Demo
17 @using (Ajax.BeginForm("GetDate", "Home", new AjaxOptions() { Confirm = "你确定要提交吗?", HttpMethod = "post", UpdateTargetId = "result", LoadingElementId = "loading", InsertionMode = InsertionMode.Replace }))18 {19
20 }21
22
23
24