ViewBag的Html.ActionLink值

时间:2014-01-09 16:43:10

标签: asp.net-mvc-4 actionlink viewbag

在ASP MVC C#中我在ViewBag.cars中推出了一个List(汽车),现在我想制作一个带有每辆汽车标题的动作链接,如下所示:

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

当我使用 @ 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.

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

3 个答案:

答案 0 :(得分:21)

这是因为car是动态的,所以它不知道适当的扩展方法是什么。如果您将title投放到string,将id投放到object,那就没关系了:

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

您的另一个选择是制作强类型的ViewModel。

答案 1 :(得分:2)

首先尝试将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 :(得分:0)

请改为尝试:

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

ps我也会使你的属性大写而不是低。