Search code examples
c#asp.netasp.net-corerazor-pagesasp.net-core-viewcomponent

How to get object from ViewComponent on post?


On my razor page project, I am using a View Component as a template for listings, like so in my html:

@foreach (var listingItem in Model.ListingItems)
{    
    @await Component.InvokeAsync("Listing", new { listingItem = listingItem })
}

where a ListingItem object is passed down to be displayed with the model:

public class ListingViewComponent : ViewComponent
{
    public ListingItem ListingItem { get; private set; }

    public IViewComponentResult Invoke(ListingItem listingItem)
    {
       return View(this);
    }
}

In this Listing view component, I have among other things a form with a post:

<form method="post">
// some stuff
</form>

So far, I am able to successfully display data and get a post. I've search for ways to pass down object from ViewComponents to Page Models on click but haven't been successful. Can this be achieved with ViewComponents or do I need to use something like partial views?

Thanks!


Solution

  • I've search for ways to pass down object from ViewComponents to Page Models on click.

    You can try to use asp-page and asp-handler to set page and handler,so that when click button,the form data will be passed to the handler of the page.

     <form method="post" asp-page="xxpage" asp-handler="xxhandler">
    // some stuff
        <input type="submit" value="submit"/>
    </form>