【问题标题】:Refresh Razor Page ViewComponent from Control class OnPost method从 Control 类 OnPost 方法刷新 Razor 页面 ViewComponent
【发布时间】:2021-07-16 04:56:43
【问题描述】:

我正在尝试从剃刀页面的 OnPost() 方法刷新 ViewComponent。使用以下代码从 razor 页面调用 ViewComponent 时,它正在正确加载:

@await Component.InvokeAsync("Menu", new { parameters... })

但是当从 OnPost() 方法的 Razor 页面代码调用时,它不起作用。我尝试按照 DontNet 教程进行操作,但无法重新加载 ViewComponent。我尝试调试代码,看方法是否调用了 InvokeAysnc() 方法,但没有调用。

这是我正在尝试的代码:

菜单视图组件

public class MenuViewComponent : ViewComponent
{
    public IViewComponentResult Invoke(param1, param2, param3)
    {
        return View(new MenuModel() { set values... });
    }
}

EditPage.cshtml.cs

public async Task<IActionResult> OnPostAsync()
{
     //DO other operations
     ViewComponent("Menu", new { param1, param2, param3 });
}

如果有人能指导我如何从 OnPost() 方法重新加载 ViewComponent,我将不胜感激。

【问题讨论】:

  • 我们可能需要查看您的 HTML/Javascript。假设您要发回表单,请添加您的标记,以便我们查看发生了什么。

标签: c# asp.net-mvc asp.net-core razor


【解决方案1】:

你可以使用ajax调用handler,重置innerHTML,这里有一个demo:

EditPage.cshtml:

@Html.AntiForgeryToken()
<div id="MenuComponent">
    @await Component.InvokeAsync("Menu", new { param1 = 1, param2 = 2, param3 = 3 })
</div>


<button onclick="change()">change</button>
@section scripts
{
    <script>
        function change() {
            $.ajax({
                type: "POST",
                url: '?handler=Change',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                contentType: "application/x-www-form-urlencoded",
            }).done(function (result) {
                document.getElementById("MenuComponent").innerHTML = result;
            });
        }

    </script>
}

EditPage.cshtml.cs:

public async Task<IActionResult> OnPostChangeAsync()
        {
            //DO other operations
            return ViewComponent("Menu", new { param1=2, param2=3, param3=4 });
        }

菜单视图组件:

public class MenuViewComponent : ViewComponent
    {

        public async Task<IViewComponentResult> InvokeAsync(int param1,int param2,int param3)
        {
            return View(new MenuModel() {Param1=param1,Param2=param2,Param3=param3});
        }

    }

MenuViewComponent 视图:

@model MenuModel
<h1>parama1:@Model.Param1</h1>
<h1>parama2:@Model.Param2</h1>
<h1>parama3:@Model.Param3</h1>

菜单模型:

public class MenuModel
    {
        public int Param1 { get; set; }
        public int Param2 { get; set; }
        public int Param3 { get; set; }

    }

结果:

【讨论】:

  • 太棒了!!...它引导我找到解决方案...我从这个链接得到了一些更清晰的想法:andriescu.nl/net-c/…
猜你喜欢
  • 2020-07-09
  • 2020-08-19
  • 2022-01-12
  • 2021-06-05
  • 2020-10-08
  • 2021-06-18
  • 2021-01-21
  • 2020-03-27
  • 2020-10-15
相关资源
最近更新 更多