为什么需要解析?

时间:2012-06-12 11:08:36

标签: asp.net-mvc parsing razor html-helper

我对在Html帮助器中解析有疑问:

我有点像:

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

我用manualy解析第一个参数到字符串:

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

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

有人可以解释一下吗?

1 个答案:

答案 0 :(得分: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)
}