问题
Is there a way to change the URL of a given action in mvc without changing the action or controller called?
If so, how would this be done on the following MapRoute:
routes.MapRoute(
"Estate.CloseDeal",
"Estate/CloseDeal/{groupId}/{paymentType}/{mortgageValue}/{province}",
new { controller = "Estate", action = "CloseDeal" },
new { groupId = "\\d+", paymentType = "\\d+", mortgageValue = "\\d+", province = "\\d+" }
);
The desired URL is: ".../estate-support/deal-closing/...". Currently it displays as ".../Estate/CloseDeal/..."
The button linking to this action looks like:
<button detail="@Url.Action("CloseDeal", new { groupId = info.GroupId })" class="orange">
EDIT 1:
Tried changing to:
routes.MapRoute(
"Estate.CloseDeal",
"estate-support/deal-closing/{groupId}/{paymentType}/{mortgageValue}/{province}",
new { controller = "Estate", action = "CloseDeal" },
new { groupId = "\\d+", paymentType = "\\d+", mortgageValue = "\\d+", province = "\\d+" }
);
This returned error: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Edit 2:
Changing the second string worked for all routes but this one - the difference being, this route has additional parameters (groupID, paymentType etc.).
回答1:
Just replace "Estate/CloseDeal"
in the second string with "estate-support/deal-closing"
- should work fine.
In this particular case it's this easy because the route is not parameterised over the controller and action names - i.e. the route doesn't have "{controller}/{action}"
in it.
回答2:
You can also apply a route directly to an action (as shown below) or controller class itself using RouteAttribute
// Your controller class
// (You could add a Route attribute here)]
public class Estate
{
// Directly apply a route (or 2?!) to this action
[Route("estate-support/deal-closing")]
[Route("clinched")] // You can add multiple routes if required
public ActionResult CloseDeal()
{
...
}
// And of course you can parameters to the route too, such as:
[Route("customers/{customerId}/orders/{orderId}")]
public ActionResult GetOrderByCustomer(int customerId, int orderId)
{
...
}
...
}
For this to work you need to enable it by calling MapMvcAttributeRoutes in RouteConfig.cs
:
public static void RegisterRoutes(RouteCollection routes)
{
// Enable mapping by attibute in the controller classes
routes.MapMvcAttributeRoutes();
...
}
More info here from docs.microsoft.com: Attribute Routing in ASP.NET
and here: C# Corner - route attribute in MVC
回答3:
You need either to update parameters of Url.Action
calls or make you route that you want to be rendered to match the parameter of Url.Action call (i.e. name should match if using Url>Action override that uses name).
Note that you may want to map old url to new one with adding route that will simply redirect to new one if you expect people could added old Urls to favorites.
来源:https://stackoverflow.com/questions/10803290/change-url-of-action-in-mvc