URL routing suggestion in asp.net mvc
I have an action link on one of my view pages
<%=Html.ActionLink("Details", "Details", new { id = Model.Id })%>
and redirects me to a page with a url like this http://localhost:1985/Materials/Details/2
, instead I would like my url to be as http://localhost:1985/Materials/Details/steel
the material name instead of the Id ... Is this possible ... This is my action method with the controller,
public ActionResult Details(int id)
{
var material = consRepository.GetMaterial(id);
return View("Details", material);
}
EDIT: I am iterating over my json object returned from jsonresult controller ....
$.each(data.Results, function() {
divs += '<a href="/Materials/Details/' + this.Id + '">Details</a>
<a href="/Materials/Edit/' + this.Id + '">Edit</a></div>';
});
My route looks like this:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Materials", action = "Index", id = "" }
);
a source to share
I would recommend that your url is
http://localhost:1985/Materials/Details/2/Steel
It looks like SO is displaying their URL as well.
Your routes will be defined as
routes.MapRoute(
"action with slug",
"{controller}/{action}/{id}/{slug}",
new {controller = "Error", action = "NotFound", id = "", slug = ""}
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Materials", action = "Index", id = "" }
);
In response to the second question in the comments "How to remove data from a link?" If you want to remove the ACTION name so the url is simple http://site/controler/id/slug
, add the following route BEFORE the call with the slug route.
routes.MapRoute(
"controller with slug",
"Materials/{id}/{slug}",
new {controller = "Materials", action = "Details", id = "", slug = ""}
);
The "slug" which will capture the word steel will be ignored by the action because you want the Id to always get stuff.
Create a route link instead of an action link like
<%= Html.RouteLink(material.Name,
"show with slug",
new { controller = "Materials",
action = "Details",
id = material.Id,
slug = Server.HtmlDecode(material.Name).Replace(" ","-")
})
%>
I replace the spaces in my bullet with a hyphen, so they are not replaced by the browser% 20.
Your ActionResult data will remain the same.
a source to share