与ASP.NET Core中的Html.RenderAction等效 [英] Equivalent of Html.RenderAction in ASP.NET Core

查看:543
本文介绍了与ASP.NET Core中的Html.RenderAction等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从我的小型ASP.NET MVC 4应用程序切换到ASP.NET Core.

I am trying to switch to ASP.NET Core from my small ASP.NET MVC 4 application.

在我的MVC 4应用程序中,我有一个使用RenderSection的Layout文件:

In my MVC 4 application, I have a Layout file that uses RenderSection as:

@RenderSection("xyz", required: false)

然后,在我的索引文件中,我有:

Then, in my Index file, I have:

@section xyz{
        @{Html.RenderAction("abc");}
    }

因此,我正在从Index调用控制器操作方法abc().方法abc()传递模型对象,并返回该模型的局部视图. 我不能使用RenderPartial,因为它需要传递模型.

So, I am calling controller action method abc() from Index. The method abc() passes a model object and returns a partial view with that model. I cannot use RenderPartial as it needs a model to be passed.

现在,在ASP.NET Core中,我没有RenderAction()方法.

Now, in ASP.NET Core, I don't have RenderAction() method.

我的问题是:如何从索引文件中调用控制器操作方法?还有其他HTML帮助器吗(尽管我看不到)?

My question is: How would I invoke a controller action method from my Index file? Is there any other HTML helper for that (although I don't see any)?

.

推荐答案

我终于能够使用ViewComponent做到这一点.因此,我没有使用RenderAction(),而是这样做了:

I was finally able to do it with ViewComponent. So, instead of RenderAction(), I did:

@section xyz{
        @await Component.InvokeAsync("abc")
    }

其中abc是abcViewComponent的类. ViewComponent看起来像:

Where abc is a class as abcViewComponent. The ViewComponent looks like:

public class abcViewComponent : ViewComponent
    {
        private DbContextOptions<MyContext> db = new DbContextOptions<MyContext>();
        public async Task<IViewComponentResult> InvokeAsync()
        {
            MyContext context = new MyContext(db);
            IEnumerable<tableRowClass> mc = await context.tableRows.ToListAsync();
            return View(mc);
        }
    }

然后,我在新文件夹"abc"下创建了一个视图,即Views/Home/Components/abc/Default.cshtml

Then, I created a view under a new folder 'abc' as Views/Home/Components/abc/Default.cshtml

要注意的是,视图名称是Default.cshtml,这就是它的工作方式.如果有人有更好的解决方案,请告诉我.

It is to be noted that the view name is Default.cshtml and that is how it worked. If anyone has any better solution, please let me know.

感谢您将我指向ViewComponent的方向.

Thanks for pointing me in the direction of ViewComponent.

这篇关于与ASP.NET Core中的Html.RenderAction等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆