skylake skylake - 2 months ago 7
C# Question

Make ModelItem clickable inside a View and send you to next page with item.Id (MVC)

For the moment User can comment a review and all comments related to its review is displaying under the review(like youtube). You can also see the

UserName
that created the comment.

What I want to do now is to make visible
UserName
clickable and send you to another page(with it's users
Id
) where you can see details about that user. I'm new to MVC and I've no clue how to do so.

The code below is my poorly attempt to do so, but gives you an idea what I had in mind:

<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Comment)
</th>
<th>
@Html.DisplayNameFor(model => model.User.UserName)
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Comment)
</td>
<td>
@Html.DisplayFor(modelItem => @Html.ActionLink(item.User.UserName, "VisitUser", new { item.User.Id }))
</td>
</tr>
}
</table>


The code below is my controller code for displaying the user:

public ActionResult VisitUser(Guid id) {

if (id == null) {
return Content("Something went wrong..");
}
User user = db.Users.Find(id);
if (user == null) {
return HttpNotFound();
}
return View(user);
}


View for
VisitUSer
looks like the View above, but without the
@Html.ActionLink..
attempt.

RouteConfig:

public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

Answer

How about

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Comment)
        </td>
        <td>
            @Html.ActionLink(item.User.UserName, 
                "VisitUser", "User", new { id = item.User.Id }, null))
        </td>
    </tr>
}