2016-03-01 65 views
1

例如,我有ViewComponent BookShelf,其主要思想是將書籍添加到書架上。組件文件:ViewComponent和他的控制器之間的交互

(〜/查看/共享/組件/書架/ 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 
    } 
} 

所以,主要問題是如何在此ViewComponent中將書名傳遞給AddBook方法?什麼應該在asp-控制器asp-action屬性?也許我不應該返回IViewComponentResult,如果我想在添加書籍後重新加載ViewComponent?

+0

是BookShelfViewComponent控制器? – Imad

+0

@Anonymous這是默認控制器_BookShelf/Default.cshtml_ –

回答

1

我不確定你是否仍然需要一個答案,但我不妨提及ViewComponents不處理HTTP請求。 ViewComponents幫助處理事物的渲染方面。您需要使用Controller來處理POST,例如「添加書籍」。

這裏是同時涉及該視圖和控制器的POST的真正原例如:

查看

<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(命名約定很重要)

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

所以,我應該只使用ViewComponents靜態渲染,像列表?而對於請求,我們仍然需要完整的控制器,它只處理數據請求,這就是全部? –

+1

如果您願意,ViewComponents仍然可以從數據庫中提取數據以在視圖中呈現。是的,您需要一個控制器來處理HTTP請求。請記住,在ASP.NET MVC中,對請求的迴應是他們的工作。您的應用中可能有其他圖層實際執行數據訪問,但這是因爲控制器會要求他們這樣做。 –