简体   繁体   中英

@Url.Action pass id segment of current url

I am developing app in the dotnet core 3.1 C# MVC.

I have URL mapping in the Startup.cs file like this:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Account}/{action=Index}/{id?}");
            });

Have one controller named Dashboard and action method Index for which I have the URL like this.

<domain>/<controller>/<action>/<id>
http://localhost:57088/Dashboard/Index/03359edbae9543b5a1bc956e9282cfb6

In Razor pages whenever I create the link using the @Url.Action to the same controller and same action, it automatically add the id segment of the URL.

@Url.Action("Index", "Dashboard");

then it create the URL like this:

http://localhost:57088/Dashboard/Index/03359edbae9543b5a1bc956e9282cfb6

But when I create the URL using @Url.Action to different controller than it does not add the id segment of the URL.

@Url.Action("DoSomething", "Photos");

then it create the URL like this:

http://localhost:57088/Photos/DoSomething

but How can I create the URL like this:

http://localhost:57088/Photos/DoSomething/03359edbae9543b5a1bc956e9282cfb6

How can I add the same id segment to different controller as using the @Url.Action?

IUrlHelper.Action has an overload which accepts an anonymous object containing route values. You need to call this overload and pass the necessary information to properly identity your action.

For example, suppose that your Id is stored in a Guid field on your Model:

public class MyModel
{
   public Guid Id { get; set; }
   // other properties
}

The call to Url.Action might look like:

@Url.Action("DoSomething", "Photos", new { id = Model.Id });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM