【问题标题】:View component refresh on button click in Razor Pages在 Razor 页面中单击按钮时查看组件刷新
【发布时间】:2021-12-08 02:50:10
【问题描述】:

我正在使用视图组件来呈现 HTML 中的字符串列表。该组件有一个按钮,单击该按钮应切换显示哪个字符串列表。单击按钮时,应该只重新加载视图组件,而不是整个页面。

我的组件列表显示正确,但我不确定如何连接按钮,以便它只刷新视图组件

在 ~ViewComponents 我有 ShowWords:

public class ShowWords : ViewComponent
{
        public IViewComponentResult Invoke(bool ShowAll)
        {
            if (ShowAll)
            {
                return View(new List<string> { "showing", "all", "of", "the", "strings" });
            } 
            else
            {
                return View(new List<string> { "not", "showing", "all", "strings" });
            }
        }
    }

在 ~Pages/Shared/Components/ShowWords 我有 Default.cshtml:

@model List<string>

<table>
    <thead>
        <tr>
            <th>STRINGS</th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < Model.Count(); i++)
        {
        <tr>
            <td>@Model[i]</td>
        </tr>
        }
    </tbody>
</table>

视图组件是这样调用的:

<vc:show-words show-all="true" />

@*How do I get this button to refresh the view component?*@
<form method="post">
    <input type="submit" value="Toggle"/>
</form>

如果我将它绑定到一个属性然后发布它,我可以让按钮工作,但这会重新加载整个屏幕,而不仅仅是视图组件。单击按钮时让视图组件刷新的最佳方法是什么?任何帮助表示赞赏。

【问题讨论】:

    标签: c# asp.net-core razor-pages asp.net-core-viewcomponent


    【解决方案1】:

    尝试使用 ajax 调用返回视图组件的操作。这里是一个演示:

    查看(将输入的类型改为按钮,这样点击按钮时不会提交表单):

    <div id="component">
    
        <vc:show-words show-all="true" />
    </div>
    
    @*How do I get this button to refresh the view component?*@
    <form method="post">
        <input type="button" value="Toggle" onclick="Refresh()"/>
    </form>
    @section scripts
    {
        <script>
            function Refresh() {
                $.ajax({
                    type: "GET",
                    url: "RefreshViewComponent",
                    success: function (data) {
                        document.getElementById("component").innerHTML = data;
                    }
                });
            }
        </script>
    }
    

    行动:

    public IActionResult RefreshViewComponent()
            {
                return ViewComponent("ShowWords", new { ShowAll = false });
            }
    

    结果:

    【讨论】:

    • RefreshViewComponent() 函数去哪了?它需要在控制器中还是应该在剃须刀页面的代码中?
    • 它在一个控制器中。
    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2013-10-10
    • 2015-07-05
    • 2012-02-29
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多