0

I'm having trouble finding the answer to this question anywhere.

I am in need of creating a form where the user can create a post and change the url to the post.

For example, if the default route is

http://www.domain.com/posts/[the-title-of-the-post]

The user can change this to

http://www.domain.com/[modified-title-of-the-post].

The [modified-title-of-the-post] can be anything the user would like to make it. This means it is no longer tied to the title of the post and not only that, but the /posts/ is gone too.

I guess I should Also mention that this should be global, meaning the user should be able to change the url (as mentioned above) for other things on the sites like, /topics/ or /blog/

Any help would be greatly appreciated,

Thanks, Hiva

1 Answer 1

2

You could create two routes in your global.asax. Something like this

routes.MapRoute("", "posts/{url}", new { controller = "Home", action = "Posts" });
routes.MapRoute("", "{url}", new { controller = "Home", action = "Posts" });

both of them point to HomeController and the action Posts

public ActionResult Posts(string url)
{

}

to handle every url you should consider to extend the RouteBase class

Something like that should do

public class CustomRouting : RouteBase
{
  public override RouteData GetRouteData(HttpContextBase httpContext)
  {
    RouteData result = null;
    string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath;

    //Handle the request
    //Compile the RouteData with your data
    result = new RouteData(this, new MvcRouteHandler());
    result.Values.Add("controller", "MyController");
    result.Values.Add("action", "MyAction");
    result.Values.Add("id", MyId);
    }
  }
  return result;
}

public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
  //I only need to handle outbound so here is ok
  return null;
}

}

The in your global.asax you register your custom route handler

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.Add(new CustomRouting());

  routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
Sign up to request clarification or add additional context in comments.

2 Comments

I guess I should Also mention that this should be global, meaning the user should be able to change the url (as mentioned above) for other things on the sites like, /topics/ or /blog/
Well than, you should probably implement your own handling of routing, maybe based on a table of a DB. Look to implement the RouteBase class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.