0

我对 Html helper 中的解析有疑问:

我有这样的:

@foreach (var item in ViewBag.News)
{
    @Html.ActionLink(item.gdt_title, "News", "News", new { lang = ViewBag.Lang, page = ViewBag.CurrentPage, id = item.gdt_id }, null)
}

所以我有一个错误:

'System.Web.Mvc.HtmlHelper<dynamic>' 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.

我通过手动将第一个参数解析为字符串来解决它:

@foreach (var item in ViewBag.News)
{
    @Html.ActionLink((String)item.gdt_title, "News", "News", new { lang = ViewBag.Lang, page = ViewBag.CurrentPage, id = item.gdt_id }, null)
}

但我不知道为什么会这样。

有人可以解释一下吗?

4

1 回答 1

2

使用 ViewBag/ViewData 是不好的做法。

您正在使用动态模型,并且item.gdt_title是动态的。正如例外所说,

扩展方法不能动态调度

您应该使用强类型视图模型。像这样的东西

public class NewsViewModel
{
    public string Lang { get; set; }
    public int CurrentPage { get; set; }
    public List<NewsItem> News { get; set; }
}

public class NewsItem
{
     public string gdt_id { get; set; }
     public string gdt_title { get; set; }
}

控制器

public ActionResult News()
{
     NewsViewModel news = new NewsViewModel();
     news.News = LoadNews();

     return View(news);
}

看法

@model NewsViewModel

@foreach (var item in Model.News)
{
    @Html.ActionLink(item.gdt_title, "News", "News", new { lang = Model.Lang, page = Model.CurrentPage, id = item.gdt_id }, null)
}
于 2012-06-12T11:16:29.000 回答