asp.net mvc中使用ajax传统的方法与mvc中方法,高手可以帮忙解释一下么?
finer 2017-12-21 08:26:53 下面代码中,传统的我感到就是无刷新更新服务器的内容,但MVC中的方法,则是跳到一个新页面去了,感觉就是刷新的更新啊,不懂,求指导,谢谢!
Ajax.cshtml
@{
ViewBag.Title = "Ajax Page";
//下面引用Jquery和unobtrusive-ajax
}
@Scripts.Render("~/bundles/jquery")
@{
//设置ajaxOptions
var ajaxOptions = new AjaxOptions()
{
OnSuccess = "SetPassSuccess",
OnFailure = "SetPassFailure",
Confirm = "设置留言审核状态为'通过'?",
HttpMethod = "Post"
};
}
<script type="text/javascript">
$(function () {
$("#alink").click(function () {
$.get("/Home/GetTime", function (response) {
$("#showInfo").html(response);
});
});
});
function SetPassSuccess() {
alert('审核通过');
location.reload();
}
function SetPassFailure(xhr) {
alert('审核失败(HTTP状态代码:' + xhr.status + ')');
}
</script>
<div class="jumbotron">
<h1>ASP.NET</h1>
</div>
<div class="row">
<div class="col-md-4">
<a id="alink" href="javascript:void(0);">①传统方式Ajax</a><br />
@Ajax.ActionLink("②MVC中使用Ajax", "GetTime", new AjaxOptions { UpdateTargetId = "showInfo" })<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 />
@Ajax.ActionLink("MVC中Ajax请求带回调执行", "ConfirmPass", new { id = 1 }, ajaxOptions)<br />
<div id="showInfo">更新区域</div>
@Ajax.ActionLink("Ajax删除数据", "DeleteUser", "Home", new { id = 1 },
new AjaxOptions()
{
UpdateTargetId = "strcontent",
HttpMethod = "Post",
Confirm = " 您确定要删除该记录吗?该操作不可恢复!"
})
</div>
</div>
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.js")
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebAppAjax.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Ajax()
{
return View();
}
/// <summary>
/// 获取系统时间 强制不缓存
/// </summary>
/// <returns></returns>
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult GetTime()
{
return Content("Now,the time is "+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);
}
}
}