【问题标题】:Redirecting to View Component page ASP.NET CORE重定向到查看组件页面 ASP.NET CORE
【发布时间】:2020-10-31 06:28:58
【问题描述】:

我最近将我的WorkShift 视图页面更改为视图组件。但是,我现在无法使用按钮进入视图组件。我的 asp-action 中应该包含什么内容才能访问我的视图组件?

我的新视图组件在 Views->Home->Components->WorkShift->Default.cshtml

我的视图页面中的按钮应该是什么样子才能进入视图组件页面?

查看:

<div class="form-row">
    <div class="form-group col-md-4">
        <a asp-action="WorkShift" class="btn btn-secondary btn-block"><i class=" fa fa-table"></i>Back to List</a>
    </div>
</div>

【问题讨论】:

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


    【解决方案1】:

    您可以要求控制器操作返回 ViewComponent。这是一个演示:

    家庭控制器:

    public IActionResult TestButton()
        {
            return View();
        }
        public IActionResult ReturnViewComponent() {
            List<notes> list = new List<notes> { new notes { Id = "1", Notes = "note1", LastModifedDate = "2020/01/01", LastModifiedBy = "Joy" }, new notes { Id = "2", Notes = "note2", LastModifedDate = "2020/01/02", LastModifiedBy = "Tommy" }, new notes { Id = "3", Notes = "note3", LastModifedDate = "2020/01/03", LastModifiedBy = "Jay" } };
            return ViewComponent("Notes", list);
        }
    

    ViewComponents/Notes.cs:

    public class Notes:ViewComponent
        {
            public async Task<IViewComponentResult> InvokeAsync(List<notes> list)
            {
                return View(list);
            }
        }
    

    ViewComponent 位置: Views/Home/Components/Notes/default.cshtml

    Views/Home/TestButton.cshtml:

    <h1>TestButton</h1>
    <div>
        <a asp-action="ReturnViewComponent" class="btn btn-secondary btn-block"><i class=" fa fa-table"></i>Back to List</a>
    </div>
    

    结果:

    【讨论】:

    • 如果我有多个视图组件怎么办?如何进入特定的视图组件
    • 例如我有 2 个视图组件位置:Views/Home/Components/Notes/default.cshtml 和 Views/Home/Components/Author/default.cshtml。我如何重定向到作者页面
    • 我已经编辑了我的答案,如果你有Notes组件,你需要在我的答案中写ViewComponents/Notes.cs。并在控制器中使用return ViewComponent("Notes", list);。如果你有作者,你可以写控制器中的 ViewComponents/Author.cs 和 return ViewComponent("Author", list);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 2018-10-21
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多