MVC AJAX

MVC中的AJAX操作原理还是基于Jquery的封装操作。

使用微软提供的Ajax请求脚本。 另创建一个MvcAjax的Action和视图。

在视图中添加:这两个脚本不能少

@*jquery脚本*@ <script src="~/Scripts/jquery-1.8.2.min.js"></script>

@*jquery隐式异步请求脚本*@ <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

AjaxOptions 类 属性:

MVC Ajax演示

//控制器里面的方法
public ActionResult Ajax() { return View(); } public ActionResult GetDate() { return Content(DateTime.Now.ToString()); }
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Ajax</title>
    @*这两个脚本不能少*@
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script>
        function color() {
            $("#h").css("color", "red");
        }
        //JQuery Ajax
        $(function () {
            $("#JQ").click(function (){
                alert("OK");
                $.post("@Url.Action("GetDate")", function (data) {
                    $("#tt").text(data);
                });
            });                                 
        });
    </script>
</head>
<body>
    <div>
        @*mvc ajax *@
        @using (Ajax.BeginForm("GetDate",new AjaxOptions(){
                     Confirm="你确定要提交吗?",
                      HttpMethod="post",  //传值方式
                       InsertionMode= InsertionMode.Replace,
                        UpdateTargetId="h", //显示数据
                         LoadingElementId="s",
                         OnSuccess="color()"       //成功后添加属性            
        }))
        {
            <input type="submit" value="GetDateTime" />
        }
        <h1 id="h"></h1>
        <img id="s" src="~/Content/Loading7.gif"  style="display:none"/>
        <input type="button" id="JQ" value="Jqury方法" />
        <span id="tt"></span>
    </div>
</body>
</html>
原文地址:https://www.cnblogs.com/Sea1ee/p/5978749.html