I would like to create dynamic urls that route to controller actions with an Id value. I've created the following route using a catch-all parameter
routes.MapRoute(
"RouteName",
"{id}/{*Url}",
new { controller = "Controller", action = "Action", id = "" }
);
This works as expected and allows me to use the following Urls:
"http://website.com/1/fake/url/path" (1 being the id that gets passed to the action method)
Does anyone know a way to achieve it this way instead without creating my own http module?:
"http://website.com/fake/url/path/1"
Thanks - Mark
That's a really difficult one, for me anyway.
Given the following route:
routes.MapRoute("Default", "{*token}",
new { controller = "Home", action = "Index", token = 0 });
Your controller and supporting classes would be something like this:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index([ModelBinder(typeof(IndexReqquestBinder))] IndexRequest request)
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = String.Format("We're looking at ID: {0}", request.ID);
return View();
}
}
public class IndexRequest
{
public Int32 ID { get; set; }
public IndexRequest(Int32 id)
{
this.ID = id;
}
}
public class IndexReqquestBinder : IModelBinder
{
public ModelBinderResult BindModel(ModelBindingContext bindingContext)
{
if ( null != bindingContext.RouteData.Values["token"] ) {
foreach ( String v in bindingContext.RouteData.Values["token"].ToString().Split('/') ) {
Int32 id = 0;
if ( Int32.TryParse(v, out id) ) {
return new ModelBinderResult(new IndexRequest(id));
}
}
}
return new ModelBinderResult(new IndexRequest(0));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With