2013-01-31 78 views
4
到控制器

我列出一堆類別的觀點:傳遞NULL參數與ActionLink的

<ul> 
    <li>@Html.ActionLink("All", "Index", "Products")</li> 
    @foreach (var item in Model.ProductCategories) 
    { 
     <li>@Html.ActionLink(item.Name, "Index", new { id = item.Id }, null)</li> 
    } 
</ul> 

如圖所示,我應該得到的類別鏈接的列表,上面一個是「所有」以及隨後的一作爲相應的類別名稱,並將ID傳遞給控制器​​。

我的控制器看起來是這樣的:

public ActionResult Index(int? id) 
{ 
    var categories = _productCategoryRepository.GetAll().OrderByDescending(f => f.Name); 
    var items = id == null 
     ? _productItemRepository.GetAll().OrderBy(f => f.Name).ToList() 
     : _productCategoryRepository.GetSingle((int)id).ProductItems.OrderBy(f => f.Name).ToList(); 

    var model = new ProductsViewModel() 
        { 
         ProductCategories = categories, 
         ProductItems = items 
        }; 

    return View(model); 
} 

所以類別應始終是相同的。但是,當idnull以及當設置了id時的特定類別的項目時,項目應該顯示每個項目。

這一切都非常好,所以當我點擊一個分類鏈接。我得到的URL是這樣的:

/產品/索引/ 3

太好了!現在我點擊「全部」鏈接,但它將我路由到/Products/Index/3,儘管我明顯沒有將參數傳遞給它。我試圖傳遞一個空值:

@Html.ActionLink("Alle", "Index", "Products", new { id = null }) 

但後來我得到的錯誤:不能分配「空」,以匿名類型屬性。

如何強制將null傳遞給我的索引控制器?

回答

8

你的控制器動作會很高興接受可空的int,所以給它一個可爲空的int像這樣!

@Html.ActionLink("Alle", "Index", "Products", new { id = (int?)null })