【问题标题】:Why is my .cshtml page rendering ViewComponent improperly为什么我的 .cshtml 页面渲染 ViewComponent 不正确
【发布时间】:2019-09-30 20:52:45
【问题描述】:

我正在尝试在 dotnet Core Razor 页面 SPA 中刷新/重新加载视图组件。

在我的主页上,我正在使用以下方法成功渲染 ViewComponent:

<div class="row>">
        <button class="btn btn-primary" id="myButton">refresh</button>
        <div id="timeDisplays" class="row">
            @await Component.InvokeAsync("DateTimeDisplay", @DateTime.Now.ToShortDateString());
        </div>
    </div>

但是当我把它放到这样的函数中时:

<script src="~/lib/jquery/dist/jquery.js" type="text/javascript"></script>
<script>
    $("myButton").on("click",
        $(function()
        {
            $("#timeDisplays").load(@await Component.InvokeAsync("DateTimeDisplay", @DateTime.Now.ToShortDateString()));
            console.log("Reloaded");

        }));
</script>

日期时间显示组件.cs

[ViewComponent(Name = "DateTimeDisplay")]
    public class DateTimeDisplayViewComponent : ViewComponent
    {
        public DateTimeDisplayViewComponent()
        {

        }

        public async Task<IViewComponentResult> InvokeAsync(DateTime date)
        {            
            return View("DateTimeStringDisplay", DateTime.Now.ToShortDateString());
        }
    }

仅供参考,这里是部分视图

@model string
    <div class="container">
        <div class="row">
            <div class="col-6 text-right">
                <label> Current Time is</label>
            </div>
            <div class="col-6 text-left">
                <p id="timeDisplay">@Model</p>
            </div>
        </div>
    </div>

加载页面时,在我点击按钮之前,它看起来像这样:

<script>
    $("#myButton").on("click",
        function()
        {
            $("#timeDisplays").load("    <div class="container">
        <div class="row">
            <div class="col-6 text-right">
                <label> Current Time is</label>
            </div>
            <div class="col-6 text-left">
                <p id="timeDisplay">5/13/2019</p>
            </div>
        </div>
    </div>
");
            console.log("Reloaded");

        });
</script>

我可以知道发生了什么。 invokeasync 正在返回 html,但似乎 jquery 正在尝试在代码块中呈现。这是我不明白的一部分,为什么它在页面加载时执行函数(为 ViewComponent 渲染 html)。不应该等到我点击按钮吗?

我考虑将 View 转换为 HTML 字符串,希望浏览器可以解释(当我用简单的 &lt;p&gt; Hello There&lt;p&gt; 替换 invokeasync 调用时,我验证了它的工作原理

【问题讨论】:

    标签: jquery .net-core razor-pages


    【解决方案1】:

    InvokeAsync 调用在页面呈现时执行。您不能使用 JavaScript 调用它。它是 C#。你可以load a partial via AJAX。也许将您的 ViewComponent 放入部分页面。

    【讨论】:

    • 我再试一次。当我尝试返回部分结果的 Handler 方法时遇到问题。
    猜你喜欢
    • 2011-03-19
    • 2014-01-23
    • 2016-04-09
    • 1970-01-01
    • 2022-06-15
    • 2021-05-28
    • 2018-04-14
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多