ViewBag的Html.ActionLink值

fra*_*sMi 4 actionlink viewbag asp.net-mvc-4

在ASP MVC C#中我在ViewBag.cars中放了一个List(汽车),现在我想用每辆汽车的标题创建一个actionlink,如下所示:

@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>
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用@ car.title或只是car.title作为值时得到的错误,我收到此错误:

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.
Run Code Online (Sandbox Code Playgroud)

我应该填写什么作为Actionlink的第一个参数?

Joh*_*ibb 22

这是因为它car是动态的,所以它不知道适当的扩展方法是什么.如果你投titlestring,并idobject,这将是罚款:

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

您的另一个选择是创建一个强类型的ViewModel.