Reputation: 7445
I have question about parsing in Html helper :
I have sth like:
@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)
}
so then I have an error:
'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.
I solve it with manualy parse first parametr to string:
@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)
}
But I don't know why it happen.
Can somebody explain it?
Upvotes: 0
Views: 159
Reputation: 39501
Using ViewBag/ViewData is bad practice.
You are using dynamic model, and item.gdt_title
is dynamic. As the exception says,
Extension methods cannot be dynamically dispatched
You should be using strongly typed view models. Something like this
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; }
}
controller
public ActionResult News()
{
NewsViewModel news = new NewsViewModel();
news.News = LoadNews();
return View(news);
}
view
@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)
}
Upvotes: 2