MVC中应用ajax的两种方式

1.控制器
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Mvcfy.Controllers
{
    public class AjaxController : Controller
    {
        //
        // GET: /Ajax/
 
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult GetTime()
        {
            return Content(DateTime.Now.ToString());
        }
 
    }
}
 
2.展示页
 
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<!DOCTYPE html>
 
<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="../../Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn1").click(function () {
                $.ajax({
                    url: "/Ajax/GetTime",
                    async:false,//默认是true 异步
                    data:"",
                    type:"get",
                    success:function(data){
                        alert(data);
                    }
                });
                alert("先出来是异步,后出来是同步");
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="button" value="得到当前时间" id="btn1" />
    </div>
</body>
</html>
 
 
 
 
 
3.微软自己的ajax
 
 
 
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Index</title>
    <%--第一步引用脚本--%>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    
 
    <script type="text/javascript">
        $(function () {
 
            $("#loading").css("display""none");
            function showOk() {
                alert("ok");
            }
        });
    </script>
 
</head>
<body>
    
<%--   第二步:写Ajax表单--%>
<%--<%: %>
<%= Html.Encode( getSTring()) %>--%>
 
    <hr/>
    <%--微软提供的ajax--%>
    <% using(Ajax.BeginForm("GetContent",new AjaxOptions()
        {
                 Confirm="是否要提交啊?",HttpMethod="Post",UpdateTargetId="resultDiv" ,
                 InsertionMode= InsertionMode.Replace,//
                 OnSuccess="showOk" ,
                 LoadingElementId="loading"
 
            // UpdateTargetId 数据更新位置的控件id    
            //OnSuccess 成功之后的回调函数
            //LoadingElementId 处理过程中显示的控件id                              
        }) )
        {
        %>
        <input type="text" name="txtName"/>
        <input type="submit" value="提交"/>
 
    <% } %>
    
    <div id="resultDiv">
        
    </div>
    <div id="loading">
        <img src="../../Content/ico_loading2.gif" />
    </div>
 
 
</body>
</html>
 
原文地址:https://www.cnblogs.com/jiayue360/p/3166949.html