URL.Action includes id when constructing URL

前端 未结 3 700
眼角桃花
眼角桃花 2020-12-15 04:40

I\'m using ASP.Net MVC. Here\'s my code snippets from a controller named Course:

public ActionResult List(int id)
{
    var viewmodel.ShowUrl = Url.Action(\         


        
相关标签:
3条回答
  • 2020-12-15 05:20

    I know this is old, but I found this first, but didn't like any of these solutions, so I kept looking and found https://stackoverflow.com/a/19110921/1130636.

    You can use UrlParameter.Optional to solve this problem

    Url.Action("Show", "Course", new { id = UrlParameter.Optional })

    0 讨论(0)
  • 2020-12-15 05:21

    Just came across the same problem and so you know, you can also just use an empty string:

    @Url.Action("Show", "Course", new { id = "" })
    
    0 讨论(0)
  • 2020-12-15 05:23

    I'm guessing in your routing, you're not specifying that id is an optional parameter. Here's the default route in a sample project.

    routes.MapRoute(
      "Default", // Route name
      "{controller}/{action}/{id}", // URL with parameters
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } //Parameter defaults
    );
    

    Note the inclusion of id = UrlParameter.Optional. Without that, you'd get the behavior you're describing because it thinks the id is mandatory.

    On a side note, if your Show action doesn't always have an id then it should be nullable or provide a default.

    public ActionResult Show(int? id)
    public ActionResult Show(int id = 0)
    

    Otherwise you'll get an error when you try loading the url without the id parameter.

    0 讨论(0)
提交回复
热议问题