Reputation:
routes.MapRoute(
name: "MyRoute",
url: "{Product}/{name}-{id}",
defaults: new { controller = "Home", action = "Product", name = UrlParameter.Optional , id = UrlParameter.Optional }
);
my routemap and i want my url in product action be like = http://localhost:13804/Wares/Product/name-id
but now is like = http://localhost:13804/Wares/Product/4?name=name
Upvotes: 0
Views: 7189
Reputation: 21
I know its late but you can use built-in Attribute Routing in MVC5. Hope it helps someone else. You don't need to use
routes.MapRoute(
name: "MyRoute",
url: "{Product}/{name}-{id}",
defaults: new { controller = "Home", action = "Product", name = UrlParameter.Optional , id = UrlParameter.Optional }
);
Instead you can use the method below.
First enable attribute routing in RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
Then in WaresController
[Route("Wares/Product/{name}/{id}")]
public ActionResult Product(string name,int id)
{
return View();
}
Then to navigate write code like this in View.cshtml file
<a href="@Url.Action("Product","Wares",new { name="productname",id="5"})">Navigate</a>
After following above steps your URL will look like http://localhost:13804/Wares/Product/productname/5
Upvotes: 1
Reputation: 218732
When defining a route pattern the token {
and }
are used to indicate a parameter of the action method. Since you do not have a parameter called Product in your action method, there is no point in having {Product}
in the route template.
Since your want url like yourSiteName/Ware/Product/name-id
where name
and id
are dynamic parameter values, you should add the static part (/Ware/Product/
) to the route template.
This should work.
routes.MapRoute(
name: "MyRoute",
url: "Ware/Product/{name}-{id}",
defaults: new { controller = "Ware", action = "Product",
name = UrlParameter.Optional, id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Assuming your Product action method accepts these two params
public class WareController : Controller
{
public ActionResult Product(string name, int id)
{
return Content("received name : " + name +",id:"+ id);
}
}
You can generate the urls with the above pattern using the Html.ActionLink helper now
@Html.ActionLink("test", "Product", "Ware", new { id = 55, name = "some" }, null)
Upvotes: 1