Reputation:
I am getting the error
the current request is ambiguous between the following action methods: System.Web.Mvc.ActionResult Foo1(System.String) on type Project.Web.Controllers.PageController System.Web.Mvc.ActionResult Foo2(System.String) on type Project.Web.Controllers.PageController
The a href calling the ActionResults are
<a href="@Url.Action("Foo1", "Page", new { page = "Foo1" })">Foo1</a>
<a href="@Url.Action("Foo2", "Page", new { page = "Foo2" })">Foo2</a>
I am basically passing the string instead of a int id ( I realise this is not the best way to do this , but that is not the issue i want to address here )
This allows me to add a string parameter to the Routing for clean urls, so my ActionResult is now
[AllowAnonymous, Route("{page}")]
public ActionResult Foo1(string page)
{
...
}
and
[AllowAnonymous, Route("{page}")]
public ActionResult Foo2(string page)
{
...
}
Why is there ambiguity when the links are being passed to different ActionResults and the parameters are different?
Upvotes: 0
Views: 5741
Reputation: 101680
You seem to be misunderstanding what the [Route]
attribute does. Your example is definitely ambiguous.
This:
[AllowAnonymous, Route("{page}")]
means "map this action to any path that has one and only one segment, and treat that segment as the page
parameter.
So all of these URLs:
http://example.com/Foo1
http://example.com/Foo2
http://example.com/SomethingElse
would be mapped to the action that has that attribute.
If you have two actions with that same route, then the MVC framework doesn't know which action to map the URL to. Both of them are valid candidates.
I think there is a simpler way to implement what you are trying to do.
In RouteConfig.cs, add a route map that doesn't include the controller name in the URL pattern:
routes.MapRoute(
name: "Pages",
url: "{action}",
defaults: new { controller = "Page", action = "Index", id = UrlParameter.Optional }
);
Add an action
parameter to your actions:
[AllowAnonymous]
public ActionResult Foo1(string action)
{
// action has the value Foo1
...
}
and
[AllowAnonymous]
public ActionResult Foo2(string action)
{
// action has the value Foo2
...
}
Remove the page
stuff from your links:
<a href="@Url.Action("Foo1", "Page")">Foo1</a>
<a href="@Url.Action("Foo2", "Page")">Foo2</a>
And you should be all set.
page
, then you can get rid of the Foo1
and Foo2
actions, and just have one action:
[Route("{page=index}")]
public ActionResult Page(string page)
{
// page is the value specified in the url
}
For links within the site, just use ordinary <a>
elements:
<a href="/Foo1">To Foo1</a>
<a href="/Foo2">To Foo2</a>
and I think that should do it.
Upvotes: 2