Search code examples
c#asp.net-mvcurlhtml.actionlink

How to get URL value in C# MVC and put it in an Html.ActionLink


So I have this page which will show an individual record from a database. So my URL will look like:

mysite.com/Vehicle/Edit/1

or it may end it 2,3,4,5 etc.. depending on the record its on. Basically I need a link in this page that will take me to another page but have the same value in the url, so it could look like:

mysite.com/Owner/Add/1

Or it could end in 2,3,4,5 etc.. depending on which record the link was in.

How do I do this using C# MVC, im using Razor if that makes any difference. Thanks


Solution

  • You'll want to use one of the Html.ActionLink helpers.

    Say you're passing in a Model to your view that has a property called Id. You could use Html.ActionLink like this:

    @Html.ActionLink("Add Owner", "Add", "Owner", new { id = Model.Id }, null)

    The first argument is the text that the link will display. The second argument is the name of the Action to call. The third argument is the name of the Controller the Action is in. The fourth argument is the route values for the Action. The fifth argument is for html attributes. Say you wanted to add a class to your link. Instead of null, you could use new { @class = "my-link-class" }. Notice the @ in front of class. That is because class is a reserved word. If you were setting style, you would just do this: new { style = "background-color: #ffffff;" }.

    All of this is assuming your Add Action takes in an int id. So something like this:

    public ActionResult Add(int id)
    {
       // Do stuff.
    }
    

    Here are the docs for the specific Html.ActionLink overload I used in my example: http://msdn.microsoft.com/en-us/library/dd504972(v=vs.108).aspx