Dynamic RouteConfig in asp.net MVC 4 - c#

I know I can change the routing in the RouteConfig in my MVC application:
routes.MapRoute(name: "epage", url: "view/SpecificURL", defaults: new {
controller = "ePage",
action = "Index"
})
but I am wondering how to redirect for values comming from a db. There is one row in my db that has titles . So for each title comming from the db I want to redirect to a specific url
ex.
the title in db may be "pink" I want www.mydomain.com/pink to be rerouted to a specific url . The URL that I want it redirected to is also in the db. I looked at lots of questions on this and can not seem to find any that dynamically change the routing of urls

You can setup a route like this:
routes.MapRoute(name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index" });
Then in your controller (the HomeController in my case):
public ActionResult Index(string id)
{
ContentResult cr = new ContentResult();
// Do a DB lookup here to get the data you need from the database to generate the appropriate content.
cr.Content = id;
return cr;
}
This example simply returns the string that was sent. So now if I browse to http://localhost/mysite/pink I would get "pink" back as my result. You could easily use this method to then do a lookup to your custom database to determine the correct content to return.
If your existing routes don't let you take this route :), then you can always do a SQL query in the RegisterRoutes method and populate the route table from that.

Related

How can I configure sub routes in MVC

I have a service in my website that loads content blocks from an external provider, from which users are are able to click links and navigate.
My routing needs to be able to handle these by calling my home controller with the request path.
For example, the url they will use to navigate will be
www../shop/hire/category/subcategory/subsubcategory/....
and if they're after a specific product:
www../shop/hire/category/subcategory/subsubcategory...?product=ABC
the constant in that, would be /shop/hire/ with the categories changing based on where you are, and the product if they have found what they are actually after.
The problem I've got, is when a link with a path like that is clicked in my application, rather than using the HomeController so I can parse the request, and call the service with the appropriate URL, I just get a 404.
I've tried adding the route:
routes.MapRoute(
name: "Category",
url: "shop/hire/{categories}/{product}",
defaults: new { controller = "Home", action = "Index", categories = UrlParameter.Optional, product = UrlParameter.Optional }
);
but this doesn't seem to have had any effect.
Try using a catch all route
routes.MapRoute(
name: "Category",
url: "shop/hire/{*categories}",
defaults: new { controller = "Home", action = "Index" }
);
and in your action you can parse the value to get your categories and product
public ActionResult Index(string catagories) { ... }

Parameters in MVC not being correctly passed into the view from routing

I'm teaching myself MVC and have an issue with routing correctly
I have a controller named "ClipsController" and 1 view inside with the name "Index" (boring, i know)
I have my routeconfig file configured with the following route:
routes.MapRoute(
"Clips",
"Clips/{id}",
new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);
which is Before the "Default" route. When i go to /Clips/ExampleID
it does hit the correct route, and does start the Index action in the Clips controller. What i'm having trouble with is the parameter 'ID' fails to pass through into the Index page, but i end up on the index action of the Clips controller, with the URL domain.my/Clips/ExampleID
I attempt to get the ID parameter with
httpcontext.current.request.querystring["id"]
which always returns a null. My actionresult in the controller is as follows:
public ActionResult Index(string id)
{
return view()
}
To reiterate, I'm not able to see the querystring id on the index view, even though the URL does the correct route, and the actionresult in the controller is to my kowledge correct. If i have done something critically wrong or you need more information please let me know, Thanks.
I attempt to get the ID parameter with
httpcontext.current.request.querystring["id"]
No, you don't have any query string parameters in this url:
http://domain.my/Clips/ExampleID
Query string parameters follow the ? character in an url. For example if you had the following url:
http://domain.my/Clips?id=ExampleID
then you could attempt to read the id query string parameter using your initial code.
With this url: http://domain.my/Clips/ExampleID you could query the id route value parameter. But using HttpContext.Current is absolutely the wrong way to do it. You should never use HttpContext.Current in an ASP.NET MVC application. Quite on the contrary, you can access this information everywhere where you have access to HttpContextBase (which is pretty much everywhere in the ASP.NET MVC application pipeline):
httpContext.Request.RequestContext.RouteData.Values["id"]
Long story short, if you needed to query the value of this parameter inside your controller action you would simply use the provided id argument:
public ActionResult Index(string id)
{
// Here the id argument will map to ExampleID
return view()
}
Also you probably don't need your custom route:
routes.MapRoute(
"Clips",
"Clips/{id}",
new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);
That's completely redundant and it is already covered by the default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
So feel more than free to get rid of your custom route.

Is it possible to have a parameter named action in MVC4?

PLEASE MARK AS DUPLICATE - Its already answered here
Is it possible to have a parameter named action in MVC4?
Trying to do this results in the parameter returning me the name of the controller action rather than the parameter value.
/Somecontroller/Someaction?action=value
When I try to access the parameter action, I get "Someaction" as the result rather than "value".
Trying to bind the parameter to a different name doesn't help either.
public ActionResult Someaction([Bind(Prefix = "action")] String id)
Edit: I have not found 'Action'/'action' in reserved MVC keywords either.
I haven't tested this, but I would assume you could try changing the url of your default route to something other than action
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
to
routes.MapRoute("Default", "{controller}/{cAction}/{id}",
new { controller = "Home", cAction = "Index", id = UrlParameter.Optional });
this should then allow you to use action as a parameter in your Action. I'm not certain why you'd want to do this, I would probably build a route url that accepted my action and built it as part of the url similar to this:
/SomeController/SomeAction/value where value is your "action" parameter.
EDIT based on comments:
I successfully created a route that goes to an aspx url'd route
routes.MapRoute(null, "third-party.aspx", new { controller = "Home", action = "Index" });
Obviously you can add whatever controller/action you want here and where you want to handle it, then you access that route via /third-party.aspx?action=value and it seemed to work for me

Load data in view based on ID in url (asp.net mvc)

I was looking for a way to load different data from the database based on an ID or name in the URL.
For example:
This is the link to the view:
http://localhost:50830/CreateSale/Order
Now I want something like this:
http://localhost:50830/CreateSale/Order/5
OR
http://localhost:50830/CreateSale/Order/Cookies
And then based on the ID (5) or the name (Cookies), the controller CreateSale will load the data that is linked to the ID/name in the Order view. This data will be different for every ID/name.
EDIT
So basically what I want is a way to create a URL like the one I showed. So when I type the link into the browser, depending on the the last part (5 or Cookie), it should show the desired data on the page.
For example:
If the link is:
http://localhost:50830/CreateSale/Order/Cookies
Then I want to see data about ordering cookies on the page.
When the link is:
http://localhost:50830/CreateSale/Order/Toys
Then I want to see data about ordering toys on the page.
Is there any way to do this in asp.net mvc4?
Thanks!
This should work out of the box with the default routing. On the controller method read the Id and pass it to your method that reads from the database, then pass the results back to the view.
public ActionResult Order(string id)
{
var data = DbLoader.Execute(id);
return View(data);
}
On your view, read the data you passed to it. e,g in Index.cshtml.
#foreach (var dataItem in Model)
{
//Display something
}
This assumes you do not have a custom route for "CreateSale/Orders" and is using the default route of :
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
If you do have a custom route for "/CreateSale/Order" ensure the url ends with "/{id}" like the default route.
EDIT
To generate urls use the Url.Action method either in your view or controller. E.g
#Url.Action("Order", "CreateSale", new RouteValueDictionary { { "id","5" } }, Request.Url.Scheme, Request.Url.Host) //generates http://localhost:50830/CreateSale/Order/5
#Url.Action("Order", "CreateSale", new RouteValueDictionary { { "id","Cookies" } }, Request.Url.Scheme, Request.Url.Host) //generates http://localhost:50830/CreateSale/Order/Cookies
#Url.Action("Order", "CreateSale", new RouteValueDictionary { { "id","Toys" } }, Request.Url.Scheme, Request.Url.Host) //generates http://localhost/CreateSale/Order/Toys

Custom Routing without changing the URL

I have a controller and a view which returns book information when I pass the ID, e.g.:
/Content/Index?id=1
Now I want to make this as a friendly URL to end user. For eg:
Books/BookName (Name of the book the Id 1 is mapped to)
So I added a route values in global.asax as :
route.maprRoute(name:"custom", url:"Books/{bookname}",
defaults: new {controller = "bookMap", action ="index"}
in "BookMap" controller I get the bookname and convert that to the ID (which is 1)
and do a redirectionToAction to Content/Index by passing the ID as a parameter.
This works fine. But the problem is I want to keep the friendly name after redirecting to the view. Now it changes to Content/Index?id=1. But I want to keep the friendly URL which is Books/BookName. How do I achieve this pls.
You can use HttpContext.RewritePath(url) to do a redirect "internally" which keeps the external URL. Use this in place of the RedirectToAction. Note however that it's not properly supported by the MVC framework at this time so it will be a little "hacky" to implement.
You should change your route for this:
routes.MapRoute(
"Books",
"book/{bookname}/{bookid}",
new { controller = "book", action = "Index", bookname = UrlParameter.Optional },
new { id = #"\d+" }
);

Categories

Resources