Html.ActionLink value for ViewBag

In ASP MVC C # I put List (Cars) in ViewBag.cars, now I want to create an actionlink with the name of each car, for example:

@if (ViewBag.cars != null)
{
    foreach (var car in ViewBag.cars)
    {
         <h4>@Html.ActionLink(@car.title, "Detail", "Cars", new { id = @car.id }, new { @class = "more markered" })</h4>
    }
}

The error that occurs when using @ car.title or just car.title as values, I get this error:

CS1973: 'System.Web.Mvc.HtmlHelper<AutoProject.Models.CarDetails>' has no applicable method named 'ActionLink' but appears to have an extension method by that name.
 Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

What should I fill in as the first Actionlink parameter?

+4
source share
3 answers

This is because it caris dynamic, so it does not know what the corresponding extension method can be. If you drop titlein stringand idin object, everything will be fine:

<h4>@Html.ActionLink((string) car.title, "Detail", "Cars", new { id = (object) car.id }, new { @class = "more markered" })</h4>

- ViewModel.

+19

car.title ,

@if (ViewBag.cars != null)
{
     foreach (var car in ViewBag.cars)
     {
        string title = car.title.ToString();
        <h4>@Html.ActionLink(title, "Detail", "Cars", new { id = @car.id }, new { @class = "more markered" })</h4>
     }
}
+2

Try this instead:

foreach (Car car in ViewBag.cars)
    {
    <h4>@Html.ActionLink(car.title, "Detail", "Cars", new { id = car.id }, new { @class = "more markered" })</h4>
}

ps I would also do your Uppercase properties, not lower.

0
source

All Articles