【问题标题】:data-ajax-update not working in dotnet core jquery unobtrusive ajaxdata-ajax-update 在 dotnet core jquery unobtrusive ajax 中不起作用
【发布时间】:2018-12-10 11:19:54
【问题描述】:

我想使用局部视图中的 ajax 数据更新容器中的数据,但页面只是重新加载而没有错误并且不会更新数据。请帮我提供建议。

这是我的控制器代码

public class HomeController : Controller
{
   public ActionResult OnGetPartial()
    {
        return PartialView();
    }
}

这是我的 PartialView 代码

<p>Hello from the Hello World partial at @DateTime.Now</p>

它是我的索引和 _layout 代码。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - IntegTest</title>              
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
            @RenderBody()       
        <script src="~/lib/jquery/dist/jquery.js"></script>              
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
        </script>                 
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    <script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>    
    @RenderSection("Scripts", required: false)
</body>
</html>

索引

<a href="" data-ajax="true" data-ajax-url="@Url.Action("OnGetPartial","Home")" data-ajax-update="#panel" data-ajax-complete="completed" data-ajax-failure="failed">Click Here!</a>
<div id="panel">        
</div>
<script>
    completed = function (xhr) {
        alert('hi ${xhr.responseText}!');
    }
    failed = function (xhr) {
        alert('Status: { xhr.status }, Status Text: { xhr.statusText}');
    }
</script>

【问题讨论】:

    标签: c# jquery ajax asp.net-core


    【解决方案1】:

    你需要使用 jQuery Unobtrusive AJAX 库,可以在 Github 找到:

    https://github.com/aspnet/jquery-ajax-unobtrusive

    您可以从上面的链接(在 src 文件夹中)下载文件或从 VS 中的 Nuget 安装它。然后你需要在你的 _layout 页面中链接文件:

    <script src="~/lib/jquery-validation-unobtrusive/jquery.unobtrusive-ajax.js"></script>
    

    之后,您的代码应该运行良好。此外,您应该确保设置了正确的局部视图名称。如果您使用的是 Razor 页面,可以参考this article 获取详细代码示例。

    【讨论】:

    • 天哪,我花了 2 天时间阅读了我能找到的关于这个库的所有文章,只是没有插入它...我检查了我的代码 200 次...我非常讨厌自己我想把头撞到墙上。
    • 非常感谢好心人,非常感谢您的回答,祝您长寿。谢谢
    • 我遇到了与@vlad 完全相同的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2013-09-16
    相关资源
    最近更新 更多