Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link to a different controller in a view

I am coding an MVC web application in C#.

How do I call an action on a controller from a view, where the action is not in the controller that loaded the view?

@Html.ActionLink("Edit", "Edit", new { id=item.BookID }) |
@Html.ActionLink("Details", "Details", new { id=item.BookID }) |
@Html.ActionLink("Add Comment","Create", "CommentController", new { bookid=item.BookID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.BookID })

The above code is loaded from a Book controller. I am wanting to call the "Create" action in the CommentController (see line 3 of my above code).

When I click on the above code, the following page is linked to: serveraddress/Book/Create?Length=17

I am trying to link to: serveraddress/Comment/Create?Length=17

like image 566
user2985419 Avatar asked Mar 04 '26 09:03

user2985419


1 Answers

The problem is that you are using the wrong overload. Replace...

@Html.ActionLink("Add Comment","Create", "CommentController", new { bookid=item.BookID })

with...

@Html.ActionLink("Add Comment","Create", "CommentController", new { bookid=item.BookID }, null)

I only added null to the end of the parameter list

like image 138
Leo Avatar answered Mar 05 '26 22:03

Leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!