Html.RenderAction equivalent in ASP.NET core

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

In my MVC 4 application, I have a layout file that uses a RenderSection like:

@RenderSection("xyz", required: false) 

Then in my index file, I:

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

So, I call the action method abc () of the controller from the index. The abc () method passes a model object and returns a partial view with this model. I cannot use RenderPartial, since it needs a model for the transfer.

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

My question is: how can I call the controller action method from my index file? Is there any other HTML helper for this (although I don't see it)?

.

+17
asp.net-mvc asp.net-core renderaction
source share
3 answers

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

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

Where abc is the class abcViewComponent. ViewComponent is as follows:

 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); } } 

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

It should be noted that the name of the view is Default.cshtml and that is how it works. If anyone has a better solution, please let me know.

Thanks for pointing me in the direction of ViewComponent.

+21
source share

Just to complete the above question, it is probably safer to pass the class name ViewComponent, as shown below:

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

and although "Default" is usually used as the resulting view, you can also return the view name if it is different from the default:

 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("YourViewName", mc); } } 
+5
source share

There is a workaround, you can use Url.Action + JQuery to render the content.

The view in which you want to display the action will look like this:

 <div id="dynamicContentContainer"></div> <script> $.get('@Url.Action("GetData", "Home")', {id : 1}, function(content){ $("#dynamicContentContainer").html(content); }); </script> 

Home controller:

 [HttpGet] public IActionResult GetData(int id) { return PartialView(id); } 

View

 @model int <span>Values from controler :</span> @Model 

If you need more control over the request, you can read more information here: jQuery.get ()

+3
source share

All Articles