Hello,
I am trying to have this kind of url
http://localhost:19901/announcements_search
instead of
http://localhost:19901/Home/Details/32/announcements_search
I have this kind of routing
routes.MapRoute(
name: "Slug",
url: "{slug}",
defaults: new { controller = "Home", action = "Details", slug = UrlParameter.Optional }
);
but it doesn't work
It gives
http://localhost:19901/?id=16
In my controller I have
public ActionResult Details(int? id, string slug)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SiteContent sitecontent = db.sitecontent.Find(id);
if (sitecontent == null)
{
return HttpNotFound();
}
if (string.IsNullOrWhiteSpace(slug))
{
slug= db.sitecontent.First(p => p.ContentID == id).Contentslug;
return RedirectToAction("/Details/" + id + "/" + slug);
}
return View();
}
I know that is wrong way because I pass the id. I don't know how to change it so to success it.
Any idea?
thank you
I would not recommend you to create Slug url without Id in it, because of two reasons.
If you still want to use it, you need code like below(If you just need slug in url no ID)
@Url.Action("Details", "Home", new { slug = item.Slug })
In your controller
public ActionResult Details(string slug)
{
Post post = db.Posts.Where(x=> x.urlslug == slug).FirstOrDefault();
//other code
}
In your RouteConfig
routes.MapRoute(
name: "PostWithSlug",
url: "{slug}",
defaults: new { controller = "Home", action = "Details" }
);
Note: This Should be placed before Default routing
Now you can call use URL like "http://localhost:57855/Your-slug-url"
In case you want to attach Id with Slug in your url follow Vikas's answer on this question https://qawithexperts.com/questions/37/how-can-i-simplify-url-in-net-mvc
This is the correct way.
Also you cannot hide Id from the URL if you want to fetch data using Id, you can either show ID & slug or only slug.
Here is the working demo of the code which is explained by @pika
You can check in the .gif, my RouteConfig,Details ActionMethod in controller and View results.
Thank you for your reply,
now I get
and my url becomes
http://localhost:19901/Home/Details
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly