Search code examples
asp.net-mvcasp.net-mvc-5asp.net-mvc-routing

Url.routeUrl returns null (I've tried same questions)


Hi everyone I wanna get url like {Controller}/{action}/{postid}-{address} but routUrl returns null please help me to solve it.(I'm newbie in MVC)

my route config is

routes.MapRoute(
            name: "Post",
            url: "Posts/Show/{postid}-{address}",
            defaults: new { controller = "Posts", action = "Index", postid = "", address = "" }
           );

and index.cshtml

<a href="@Url.RouteUrl("Post",new {item.PostId,item.Address })">@item.PostTitle</a>

the url that generate is http://localhost:59066/Posts/Show/1-Post-with-Featured-Image

but in PostsController

public ActionResult Show(string add)
    { return View();} 

"string add" is null !


Solution

  • I changed the route to

    routes.MapRoute("Post", "post/{postid}-{address}", new { controller = "Posts", action = "Show" ,postid="",address=""}, namespaces);
    

    and added a route with same controller and action

    routes.MapRoute("PostAddress", "post/{IdAndAdd}", new { controller = "Posts", action = "Show" }, namespaces);
    routes.MapRoute("Post", "post/{postid}-{address}", new { controller = "Posts", action = "Show" ,postid="",address=""}, namespaces);
    

    then action received "idAndAdd" correctly

    public ActionResult Show(string idAndAdd)
        {
            var parts = SeperateAddress(idAndAdd);
            if (parts == null)
                return HttpNotFound();
    
            var post = db.Posts.Find(parts.Item1);
            if (post == null)
                return HttpNotFound();
    
            if (!post.Address.Equals(parts.Item2, StringComparison.CurrentCultureIgnoreCase))
                return RedirectToRoutePermanent("Post", new { postid = parts.Item1, address = post.Address });
    
            return View(post);
        }
    
        and it's worked .