Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.ActionLink and @Html.DisplayFor at the same time (not right, but it describes what I want to do)

Tags:

I have the following table located in a view within a controller named Student (/Student/Details/1):

    @foreach (var item in Model.Enrollments)     {         <tr>             <td>                 @Html.DisplayFor(modelItem => item.Course.Title)             </td>             <td>                 @Html.DisplayFor(modelItem => item.Grade)             </td>         </tr>     } 

I would like to make each table definition into a link that takes me to a view within a controller named Course (/Course/Details/1).

I have tried things along the lines of:

@Html.ActionLink(Html.DisplayFor(modelItem => item.Course.Title, "Details", "Course")) 

in place of

@Html.DisplayFor(modelItem => item.Course.Title) 

Which does not compile. How would I appropriately display my model's title along with a link to the details of the referenced title?

like image 514
Ecnalyr Avatar asked Mar 06 '12 13:03

Ecnalyr


People also ask

What is difference between HTML ActionLink and URL action?

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

What does HTML ActionLink do?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.


2 Answers

If I understand right your question, you want a link with the text of the course.

This should work:

  @Html.ActionLink(item.Course.Title, "Details", "Course") 

If you want to pass the ID of the course to the controller (assuming your routing rules are set correctly and the Id is something like: item.Course.Id)

  @Html.ActionLink(item.Course.Title, "Details", "Course", new { Id = item.Course.Id }, null /* html attributes */) 

If you need to use the UIHint attribute on the property, to add extra formatting, you can use this

  <a href="@Url.Action("Details", "Course", new { Id=item.Course.Id})">@Html.DisplayFor(modelItem => item.Course.Title)</a> 
like image 198
Iridio Avatar answered Sep 20 '22 22:09

Iridio


You forgot an ) after Html.DisplayFor(modelItem => item.Course.Title.

Maybe try adding a .ToString() to it might help.

like image 31
kows Avatar answered Sep 21 '22 22:09

kows