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

北战南征 提交于 2021-02-06 14:59:37

问题


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?


回答1:


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>



回答2:


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

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




回答3:


// you want to use link with the displaying a course. you can use.

<a href = "@url.action("Details","course",new {Id = item.Course.Id}
@html.displayfor(m => m.Course.Title)</a>

// second approach

 @Html.ActionLink(item.Course.Title, "Details", "Course", new { Id = item.Course.Id })


来源:https://stackoverflow.com/questions/9584673/html-actionlink-and-html-displayfor-at-the-same-time-not-right-but-it-descri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!