Search code examples
c#asp.net-coreasp.net-core-viewcomponent

Interaction between ViewComponent and his Controller


For example, I have ViewComponent BookShelf, which main idea is to add books to shelf. Components files:

(~/Views/Shared/Components/BookShelf/Default.cshtml)

<form id="addForm" asp-controller="?" asp-action="?" role="form" method="post"> 
    <input type="text" name="bookName" value="exampleValue"/ >
    <button type="submit"> Add book </button>
</form>

(~/ViewComponents/BookShelfViewComponent.cs)

public class BookShelfViewComponent : ViewComponent
{
    private readonly ApplicationDbContext _dbContext;

    public RoleManagementViewComponent(
        ApplicationDbContext context)
    {
         _dbContext = context;
    }

    public IViewComponentResult Invoke()
    {
        return View();
    }

    public IViewComponentResult AddBook(string bookName)
    {
         //Some database logic to add book
    }
}

So, the main question is how to pass book name to AddBook method in this ViewComponent? What should be in asp-controller and asp-action attributes? And maybe i shouldn't return IViewComponentResult, if I want to reload ViewComponent after adding book?


Solution

  • I'm not sure if you still need an for an answer on this, but I might as well mention that ViewComponents don't handle HTTP requests. ViewComponents help deal with the rendering side of things. You'll want to use a Controller to handle POSTs such as "adding a book".

    Here is a really raw example of a POST involving both the view and a controller:

    View

    <form asp-controller="Items" asp-action="Create">
        <input type="text" name="item" value="exampleValue" />
        <input type="submit" value="Create" class="btn btn-default" />
    </form>
    

    ItemsController (naming convention important)

        // POST: Items/Create
        [HttpPost]
        public IActionResult Create(string item)
        {
            //do you string db thing
        }