【问题标题】:Asp.net core .click() events are not working in partial viewAsp.net core .click() 事件在部分视图中不起作用
【发布时间】:2020-07-27 15:31:25
【问题描述】:

在局部视图中,当单击 html 元素时,我正在调用 jquery .click() 事件,但这些事件并未触发。但是当我在主视图中放置相同的代码时,它们正在工作。请帮助我

以下是事件。

$('.page-change').click(function (e) {
            alert("Hello page");
        });

        $('.toggle-sort').click(function (e) {
            alert("Hello");
        });

Please click on this link which will show output with highlighted areas for on click event which should get called

以下是我完成的步骤:

从常规视图页面调用局部视图。 当我点击标题 EmployeeName 应该触发相关的 .click() 事件,但该事件不起作用。

如果我将部分视图的代码放在 index.cshtml 中,那么 .click() 事件就会起作用。

Controller:将视图模型数据传递给索引 cshtml 的 HomeController

      public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            var res = new List<EmployeeViewModel>() { 
                new EmployeeViewModel() { EmployeeDepartment = "Development", EmployeeName = "Sarath" },
            new EmployeeViewModel (){ EmployeeDepartment="Sales",EmployeeName="Stephen"},
            new EmployeeViewModel (){ EmployeeDepartment="Human Resource",EmployeeName="Krishna"},
            new EmployeeViewModel (){ EmployeeDepartment="Development",EmployeeName="Naresh"}};
            return View(res);
        }
}

查看:Index.cshtml

@model IEnumerable<EmployeeViewModel>

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Employees Data</h1>

    <div class="row">
        <div class="col my-3">
            <partial name="_EmployeesDataPartial" model="Model" />
        </div>
    </div>

</div>

部分视图_EmployeesDataPartial.cshtml

    @model IEnumerable<RandDpartialView.Models.EmployeeViewModel>


<table class="table">
    <thead>
        <tr>
            <th class="th--sortable toggle-sort" style="cursor:pointer">
                @Html.DisplayNameFor(model => model.EmployeeName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmployeeDepartment)
            </th>            
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.EmployeeName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EmployeeDepartment)
                </td>               
            </tr>
        }
    </tbody>
</table>
<div>
    <ul class="pagination" style="cursor:pointer">
        <li class="pagination-item">
            <a class="pagination-link page-change" data-page="1">
                <span class="icon fa fa-fw fas fa-angle-double-left"></span><span class="text">&nbsp;First</span>
            </a>
        </li>
    </ul>
</div>

@section Scripts{
    <script type="text/javascript">

        $(function () {

            $('.page-change').click(function (e) {
                alert("Hello page");
            });

            $('.toggle-sort').click(function (e) {
                alert("Hello");
            });
        });
    </script>
}

【问题讨论】:

    标签: javascript asp.net-mvc asp.net-core partial-views


    【解决方案1】:

    @section 在部分中不起作用。这里有一篇文章:

    https://www.adamrussell.com/asp-net-core-section-scripts-in-a-partial-view/

    作者使用 HtmlHelper 类模仿行为:

    using System;
    using System.Linq;
    using System.Text.Encodings.Web;
    using System.Text.RegularExpressions;
    using Microsoft.AspNetCore.Html;
    using Microsoft.AspNetCore.Mvc.Razor;
    using Microsoft.AspNetCore.Mvc.Rendering;
    public static class HtmlHelperExtensions
    {
        private const string _partialViewScriptItemPrefix = "scripts_";
        public static IHtmlContent PartialSectionScripts(this IHtmlHelper htmlHelper, Func<object, HelperResult> template)
        {
            htmlHelper.ViewContext.HttpContext.Items[_partialViewScriptItemPrefix + Guid.NewGuid()] = template;
            return new HtmlContentBuilder();
        }
        public static IHtmlContent RenderPartialSectionScripts(this IHtmlHelper htmlHelper)
        {
            var partialSectionScripts = htmlHelper.ViewContext.HttpContext.Items.Keys
                .Where(k => Regex.IsMatch(
                    k.ToString(),
                    "^" + _partialViewScriptItemPrefix + "([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$"));
            var contentBuilder = new HtmlContentBuilder();
            foreach (var key in partialSectionScripts)
            {
                var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
                if (template != null)
                {
                    var writer = new System.IO.StringWriter();
                    template(null).WriteTo(writer, HtmlEncoder.Default);
                    contentBuilder.AppendHtml(writer.ToString());
                }
            }
            return contentBuilder;
        }
    }
    

    替换@section

    @Html.PartialSectionScripts(
        @<script>
            alert('Hello from the partial view!');
        </script>
    )
    

    并添加调用以渲染脚本:

        @*...*@
        @RenderSection("Scripts", required: false)
        @Html.RenderPartialSectionScripts()
    </body>
    </html>
    

    【讨论】:

    • 嗨@Matthew Jaspers 感谢您的回复。我会检查您的建议并通知您。
    • 嗨@Matthew Jaspers 我收到一个编译时错误,我觉得我做错了什么。这是我所做的步骤,创建了一个帮助程序类,然后在 _Layout.cshtml 中添加 Html.RenderPartialSectionScripts() 并在部分视图“_EmployeesDataPartial.cshtml”中添加 Html.PartialSectionScripts,但编译时错误出现在上面两行错误消息:在 main查看 IHtmlHelper> 不包含 RenderPartialSectionScripts 的定义相同的错误在 PartialSectionScripts 的局部视图中
    • @RAMG 听起来您需要导入已声明 HtmlHelper 的命名空间。见stackoverflow.com/questions/3239006/…
    • 是的,我错过了导入命名空间。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 2022-10-01
    • 2018-12-05
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多