我正在研究asp.net MVC 2应用程序。我有一个ajax.action链接,但它无法正常工作。我在我看来有这个代码:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<script type="text/javascript">
function success(result) {
alert(result);
// TODO: do something with the object
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%: Ajax.ActionLink(
"Delete",
"Delete",
new { Id = 55 },
new AjaxOptions { OnComplete = "success" })
%>
</asp:Content>
这是控制器代码:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public JsonResult Delete(Int32 Id) {
return Json("Record deleted!", JsonRequestBehavior.AllowGet);
}
但是当我点击链接时,它会显示已删除的记录!在浏览器中而不是显示为警报。我错过了一些文件吗?
答案 0 :(得分:0)
您可能需要在页面中加入MicrosoftAjax.js
和MicrosoftMvcAjax.js
脚本:
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
在ASP.NET MVC 3及更高版本中,这些文件是jQuery不引人注目的脚本obsolete and replaced
。
现在您已经通过邮件向我发送了示例项目,很明显问题是什么。您已在页面的<title>
标记内定义了您的成功JavaScript功能,这显然无效。
因此,在您的MasterPage中,您应该为脚本定义一个特殊的占位符(另请注意我如何使用url帮助程序修复了CSS文件的硬编码链接):
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="<%= Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
<asp:ContentPlaceHolder ID="Scripts" runat="server" />
</head>
您可以在视图中覆盖:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Scripts" runat="server">
<script type="text/javascript">
function success() {
alert('success');
// TODO: do something with the object
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Ajax.ActionLink(
"Delete",
"Delete",
new { id = 55 },
new AjaxOptions { OnComplete = "success" }
) %>
</asp:Content>