不引人注意的AJAX错误:"未捕获的ReferenceError:未定义系统"

Nic*_*oad 13 ajax asp.net-mvc unobtrusive-ajax asp.net-mvc-5

示例代码:在Visual Studio的MVC 5项目中,我设置了以下控制器和视图:

调节器

TestController.cs

public class TestController : BaseController
{
    public ActionResult Index()
    {
        return View("Index");
    }

    public PartialViewResult MyPartialView1()
    {
        return PartialView("PartialView1");
    }

    public PartialViewResult MyPartialView2()
    {
        return PartialView("PartialView2");
    }
}
Run Code Online (Sandbox Code Playgroud)

查看

Index.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <script src="@Url.Content("~/Scripts/jquery-2.1.1.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>
</head>
<body>
    <h1>Testing Unobtrusive AJAX</h1>
    @Ajax.ActionLink("Partial 1", "MyPartialView1", "Test",
                new AjaxOptions() { UpdateTargetId = "contentShouldLoadHere", InsertionMode = InsertionMode.Replace })
    |
    @Ajax.ActionLink("Partial 2", "MyPartialView2", "Test",
                new AjaxOptions() { UpdateTargetId = "contentShouldLoadHere", InsertionMode = InsertionMode.Replace })
    <div id="contentShouldLoadHere">
         <p>This will get replaced.</p>
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

PartialView1.cshtml

<h1>Test 1</h1>
Run Code Online (Sandbox Code Playgroud)

PartialView2.cshtml

<h1>Test 2</h1>
Run Code Online (Sandbox Code Playgroud)

如果我已正确理解,单击"Partial 1"应将"PartialView1"的内容加载到ID为"contentShouldLoadHere"的HTML元素中.相反,单击"部分1"会导致MyPartialView1操作的正常页面加载(~/Test/MyPartialView1)在Chrome开发工具控制台中,我收到以下JavaScript错误:

Uncaught ReferenceError: Sys is undefined
Run Code Online (Sandbox Code Playgroud)

有谁知道这是为什么,以及我如何解决它?

注意 - 我已通过Chrome Dev Tools确认两个脚本都已正确加载. - @Ajax助手生成的链接的HTML是:

<a href="/Test/MyPartialView1" onclick="Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;contentShouldLoadHere&#39; });">Partial 1</a>
Run Code Online (Sandbox Code Playgroud)

小智 32

如果禁用了不显眼的javascript,则会生成为链接生成的html.您可以在视图中启用它

@{HtmlHelper.UnobtrusiveJavaScriptEnabled = true;}
Run Code Online (Sandbox Code Playgroud)

或申请(in web.config)with

<configuration>
  <appSettings>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Run Code Online (Sandbox Code Playgroud)

你呈现的HTML应该是这样的

<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#contentShouldLoadHere" href="/Test/Partial1">Partial 1</a>
Run Code Online (Sandbox Code Playgroud)

并将使用该jquery.unobtrusive-ajax.js文件

  • 您也可以在Global.asax.cs中放置`HtmlHelper.UnobtrusiveJavaScriptEnabled = true;`. (4认同)