Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass null parameter to controller with ActionLink

I have a view that lists a bunch of categories:

<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>

As shown I should get a list of category links, the top one being "All" and the following ones being the respective category name, with an id passed to the controller.

My controller looks like this:

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

So the categories should always be the same. But the items should show every item, when the id is null and the items of the specific category when the id is set.

That all works absolutely great, so when I click a category link. I get to the url like this:

/Products/Index/3

Great! Now I click the "All" link, but it's routing me to /Products/Index/3 even though I clearly don't pass a parameter to it. I tried passing a null value:

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

But I then get the error: Cannot assign 'null' to anonymous type property.

How can I force null to be passed to my index controller?

like image 564
Daniel Olsen Avatar asked Jan 31 '13 23:01

Daniel Olsen


1 Answers

Your controller action will be happy enough to accept a nullable int, so give it a nullable int like so!

@Html.ActionLink("Alle", "Index", "Products", new { id = (int?)null })
like image 131
David Spence Avatar answered Oct 07 '22 04:10

David Spence