默认情况下,Visual Studio 2013新建ASP.NET MVC5项目,不包含jquery.unobtrusive-ajax.js,需要手工添加。
点击Visual Studio 2013中的“工具”菜单,选择“库程序包管理器”,再选择“管理解决方案的NuGet程序包“,在出现的对话框中联机搜索jquery.unobtrusive-ajax.js,然后安装即可。
看上图中的信息,对应版本是3.2.0,需要jQuery1.8以上版本支持。MVC5中默认包含的jQuery1.10.2,可以满足条件。
接下来,我们就可以使用AjaxHelper了。
View代码:
@model MVCLearning.Models.SetPasswordModel @{
ViewBag.Title = "修改密码";
}
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10..js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script type="text/javascript">
function Show(msg) {
alert(msg);
}
</script> @using (Ajax.BeginForm("Edit", new AjaxOptions(){OnSuccess="Show"}))
{
@Html.AntiForgeryToken()
<br />
<div class="form-horizontal">
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
} @section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
别忘了在View中引用脚本:
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10..js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
Controller代码:
[HttpPost]
public ActionResult Edit(SetPasswordModel model)
{
try
{
string userName=User.Identity.Name;
var user= db.User.Where(x => x.UserName == userName).FirstOrDefault();
if(model.Password!=user.Password)
{
ModelState.AddModelError("","原始密码错误!");
return View(model);
}
else
{
user.Password = model.NewPassword;//更新密码
db.SaveChanges();
return Content("密码修改成功!");
}
//return RedirectToAction("Index","ContactGroup");
}
catch
{
return View(model);
}
}
也可以在Controller中直接返回JavaScript,代码如下:
View代码修改如下:
@using (Ajax.BeginForm("Edit",new AjaxOptions()))
Controller代码修改如下:
return JavaScript("alert('密码修改成功!');");