Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.ActionLink value of ViewBag

In ASP MVC C# I putted a List(Cars) in the ViewBag.cars, now I want to make an actionlink with the title of each car, like this:

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

The error I get when I use @car.title or just car.title as value, I get this error:

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.

What should I fill in as first parameter of the Actionlink?

like image 422
francisMi Avatar asked Jan 09 '14 16:01

francisMi


People also ask

What is HTML ActionLink ()?

ActionLink(HtmlHelper, String, String, String, String, String, String, Object, Object) Returns an anchor element (a element) for the specified link text, action, controller, protocol, host name, URL fragment, route values, and HTML attributes.

How do you call a ViewBag in Cshtml?

cshtml view, you can access ViewBag. TotalStudents property, as shown below. Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.

How do I pass an object in ActionLink?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to send Model data (object). Hence in order to pass (send) Model data (object) from View to Controller using @Html.

What is difference between HTML ActionLink and URL action?

There is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.


2 Answers

It's because car is dynamic, so it doesn't know what the appropriate extension method could be. If you cast title to string, and id to object, it'll be fine:

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

Your other option is to make a strongly typed ViewModel.

like image 166
John Gibb Avatar answered Sep 20 '22 17:09

John Gibb


Try to assign your car.title to a variable first then use that variable

@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>
     }
}
like image 42
Selman Genç Avatar answered Sep 18 '22 17:09

Selman Genç