在ASP.NET MVC中实现AJAX
程序员文章站
2024-02-29 09:08:01
...
DemoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCAjax.Controllers
{
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
return View();
}
/// <summary>
/// 获取系统时间 强制不缓存
/// </summary>
/// <returns></returns>
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult GetTime()
{
return Content(DateTime.Now.ToString());
}
[HttpPost]
public ActionResult GetPostStr(FormCollection form)
{
string userName = form["username"];
string userAge = form["userage"];
return Content(userName + userAge);
}
/// <summary>
/// 删除用户
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult DeleteUser()
{
//省略操作部分
return JavaScript("alert('删除成功')");
}
public ActionResult ConfirmPass(int id)
{
//省略操作部分
return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
}
/*
需安装Microsoft jQuery Unobtrusive Ajax 这个 NuGet 插件
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
AjaxOptions中还有其他可以指定的属性:
Confirm 等效于javascript中的return confirm(msg),在点击该链接时先提示需要确认的信息。
HttpMethod 指定使用Get或者是Post方式发送Http请求
InsertMode 指定使用何种方式在指定的元素更新数据,"InsertAfter", "InsertBefore", or "Replace" 默认为:Replace
LoadingElementDuration Loading元素显示的时间
LoadingElementId 可以指定在Http请求期间显示的Loading元素
OnBegin 在Http请求之前执行的javascript方法
OnComplete 在Http请求结束时执行的方法
OnFailure 在Http请求失败时执行的方法
OnSuccess 在Http请求成功时执行的方法
UpdateTargetId Http请求更新的页面元素
Url Http请求的Url
*/
}
}
Index.cshtml
@{
Layout = null;
}
@{
//设置ajaxOptions
var ajaxOptions = new AjaxOptions()
{
OnSuccess = "SetPassSuccess",
OnFailure = "SetPassFailure",
Confirm = "设置留言审核状态为'通过'?",
HttpMethod = "Post"
};
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
$(function () {
$("#alink").click(function () {
$.get("/Demo/GetTime", function (response) {
$("#showInfo").html(response);
});
});
});
function SetPassSuccess() {
alert('审核通过');
location.reload();
}
function SetPassFailure(xhr) {
alert('审核失败(HTTP状态代码:' + xhr.status + ')');
}
</script>
</head>
<body>
<div>
<a id="alink" href="javascript:void(0);">①传统方式Ajax</a><br /><br />
@Ajax.ActionLink("②MVC中使用Ajax", "GetTime", new AjaxOptions { UpdateTargetId = "showInfo" })<br /><br />
@using (Ajax.BeginForm("GetPostStr", new AjaxOptions { UpdateTargetId = "showInfo" }))
{
<input type="text" name="username" /><br />
<input type="text" name="userage" /><br />
<input type="submit" value="③MVC Post方式提交Ajax" />
}
<br /><br />
@Ajax.ActionLink("MVC中Ajax请求带回调执行", "ConfirmPass", new { id = 1 }, ajaxOptions)<br /><br />
<hr />
<div id="showInfo">更新区域</div>
<hr />
@Ajax.ActionLink("Ajax删除数据", "DeleteUser", "Demo", new { id = 1 },
new AjaxOptions()
{
UpdateTargetId = "strcontent",
HttpMethod = "Post",
Confirm = " 您确定要删除该记录吗?该操作不可恢复!"
})
</div>
</body>
</html>
运行结果如图:
实体类:
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCAjax.Models
{
public class Product
{
public string ProdCode { get; set; }
public string ProdName { get; set; }
public int ProdQty { get; set; }
}
}
AjaxController.cs
using MVCAjax.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCAjax.Controllers
{
public class AjaxController : Controller
{
IEnumerable<Product> prodList = new List<Product>
{
new Product { ProdCode = "P001", ProdName = "Mobile", ProdQty = 75 },
new Product { ProdCode = "P002", ProdName = "Laptop", ProdQty = 125 },
new Product { ProdCode = "P003", ProdName = "Netbook", ProdQty = 100 },
};
// GET: Ajax
public ActionResult Index()
{
return View();
}
public PartialViewResult ShowDetails()
{
System.Threading.Thread.Sleep(3000);
string code = Request.Form["txtCode"];
Product prod = new Product();
foreach (Product p in prodList)
{
if (p.ProdCode == code)
{
prod = p;
break;
}
}
return PartialView("_ShowDetails", prod);
}
}
}
Index.cshtml
@{
Layout = null;
}
@{
var ajaxOption = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "div1",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "waitimage"
};
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div>
@using (Ajax.BeginForm("ShowDetails", "Ajax", ajaxOption))
{
<h1>输入产品Code</h1>
<h2>
产品Code: @Html.TextBox("txtCode")<br />
<input type="submit" value="Show Details" />
<input type="reset" value="Clear" />
</h2>
}
</div>
<div id="div1">
</div>
</body>
</html>
_ShowDetails.cshtml
@model MVCAjax.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_ShowDetails</title>
</head>
<body>
<div>
@if (Model.ProdCode == null)
{
<h1>无效的产品Code</h1>
}
else
{
<h1>产品详情</h1>
<h2>
产品Code: @Model.ProdCode<br />
产品名称: @Model.ProdName<br />
产品数量: @Model.ProdQty<br />
</h2>
}
</div>
</body>
</html>
运行结果如图:
下一篇: python中requests小技巧