Pass null parameter to controller with ActionLink
Asked Answered
E

1

5

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?

Exsect answered 31/1, 2013 at 23:14 Comment(0)
B
10

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 })
Bartz answered 1/2, 2013 at 3:28 Comment(1)
Nice, thank you! It did not come to my mind that I can cast it inside anonymous object and it will recognize the type that way.Lianeliang

© 2022 - 2024 — McMap. All rights reserved.