Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL.Action includes id when constructing URL

Tags:

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("Show", "Course");       ... }  public ActionResult Show(int id) {   ... } 

viewmodel.ShowUrl picks up whatever the value is of the "id" parameter. So viewmodel.ShowUrl becomes "/Course/Show/151" (value of id is 151); I want to be able to set the id part on the client based on user interaction. I want the value of viewmodel.ShowUrl to be "/Course/Show".

This seems like a bug to me. I'm not telling Url.Action to include an id value. It's doing it on its own. If I want to set the id value then I would do something like this:

var viewmodel.ShowUrl = Url.Action("Show", "Course", new {id = somevalue}); 

So, how do you prevent MVC from adding the id value? I can hardcode viewmodel.ShowUrl to "/Course/Show" but that seems to be a kludgy solution. Thanks.

like image 657
Tom Schreck Avatar asked Apr 17 '12 22:04

Tom Schreck


People also ask

What does url action?

A URL action is a hyperlink that points to a web page, file, or other web-based resource outside of Tableau. You can use URL actions to create an email or link to additional information about your data. To customize links based on your data, you can automatically enter field values as parameters in URLs.

What is the difference between url action and HTML action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

What is url in ASP NET MVC?

URL Routing is used for directing the HTTP request (generated by the user) to the respective controller in ASP.NET MVC. Whenever a user types some url in the browser and hit enter then an HTTP request is generated and this HTTP request is then handled by the controller.


2 Answers

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

@Url.Action("Show", "Course", new { id = "" }) 
like image 62
Ben Cull Avatar answered Oct 22 '22 00:10

Ben Cull


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 })

like image 31
borigas Avatar answered Oct 22 '22 02:10

borigas