custom url in asp .net mvc - asp.net-mvc

I am new to ASP.NET-MVC and I am trying to create a simple blog application. I want to use a custom url for the blog's details pages.
Right now the url for blog's details pages are the standard 'localhost/Blog/Details/3', but I want to actually use the url 'localhost/Blog/2012/06/blog-title', basically using 'localhost/Blog/{year}/{month}/{BlogTitle}'
I have tried looking on the internet but I do not understand how to do this and am not able to get a simple tutorial on how either.

You can create a new route in Global.asax.cs as below,
routes.MapRoute(
"Post", // route-name
"Blog/{year}/{month}/{BlogTitle}", // format
new { controller = "Books", action = "Post" }, // controller & action
new { year = #"\d{4}", month = #"\d{2}" } // constraints
);

You have to map a custom route
routes.MapRoute(
"Default", // Route name
"Blog/{action}/{month}/{BlogTitle}", // URL with parameters
new {controller ="MyController"}
);
Any url of type localhost/Blog/text/text/text will map to this route
this url will call MyController.Action(month,BlogTitle)
Make sure to put the more restrictive routes first becouse the first route that matches the url will be considered (from top to bottom)

Related

MVC3 Catch all path segments in URL

I'm trying to embed a legacy Area of our MVC3 application into an iframe within the website's new root layout.
The aim is to save time and avoid Javascript and CSS styling conflicts between new and old sections of the website.
I have so far been able to conditionally redirect traffic from the old Area to a new URL within the OnActionExecuting method in the Area's controllers.
e.g. http://localhost:80/Area/Account/Profile to http://localhost:80/App/Area/Account/Profile
My trouble now is setting up a catch all route that can pass the entire URL to a specific action and controller so I can take the URL and apply it to the iFrame.
I have this in my routing but it does not pass the path to the action and if there is more than one segment in the path it does not hit the route at all:
routes.MapRoute(
"AppRedirect", // Route name
"App/{*page}", // URL with parameters
new { controller = "Home", action = "App", page = UrlParameter.Optional }
);
Is there a way a can get the route working with the full path including all segments?
Or is there a better way to embed one of the projects Areas into an iFrame within the new root layout, while maintaining a readable URL similar to the old configuration? I do not want to modify the structure or routing configuration of the old Area if it can be helped.
Do you know how many possible segments there could be in the URLs? You could set up several routes (heirarchically - most segments filtering down to one) pointing to the same controller action and do the rest in there.
routes.MapRoute(
"AppRedirect2", // Route name
"App/{seg1}/{seg2}", // URL with parameters
new { controller = "Home", action = "App", seg1 = UrlParameter.Optional, seg2 = UrlParameter.Optional }
);
routes.MapRoute(
"AppRedirect1", // Route name
"App/{seg1}", // URL with parameters
new { controller = "Home", action = "App", page = UrlParameter.Optional }
);
etc...

Hide params in url by asp.net mvc routing

I have an asp.net mvc 2 application. I get a page with the url http://localhost/Object/ChangeObject/108?MtRid=216584. I want to route it like this: http://localhost/Object/ChangeObject.
How to write a route for this?
There are more than one way to do this:
Try to modify the methode "application_beginrequest" of "Global.asax" This method is called every time some request is made to the website.
Take a look at this example
URL Routing - By adding custom URL Route mapping rules before the default one as described in this article
try this
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/{MtRid}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, MtRid = UrlParameter.Optional} // Parameter defaults
);

How does MVC routing understands the URL?

Global.asax.cs has the following code on initialization:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
What I'm asking is, how does it know that what it gets for "{controller}" will be the name of the Controller class to be invoked? Are there tokens defined somewhere? if so, can I list them?
If I define additional tokens (like "{lang}") will it assume they are additional parameters?
(I'm developing a custom URL rewrite/redirect handler, and I need it to work with MVC...)
What is the most practical way to define custom patterns and "aliases" for URLs?
The Mvc runtime has the controller and action tokens hardcoded. In addition there is also "area" but thats about it.
#TDaver If I define additional tokens (like "{lang}") will it assume they are additional parameters?
yes. If you define, for instance, a parameter like lang, it wil detect it. Think about like that, it will be the querystring field called lang of the page. and you can create a route for a pretyy url. Like below;
routes.MapRoute(
"Default", // Route name
"{lang}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
so the url will be like ; http://example.com/en/home/about
Also, the most important part of routing is to understand that the routes will be picked by order. for instance, if you have multiple routes matching your current request, the first route will be picked by MVC Framework.
I reccomend you to have a look at phil haccked's RouteDebugger
Also you can create route constraints for advanced routing options as well.

ASP.NET MVC App Routing Not Working For Dynamic Data WebForm Pages

I need the correct Global.asax settings in order for my Dynamic Data site to run under an ASP.NET MVC project. The routing currently appears to be my issue.
Here is my global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
MetaModel model = new MetaModel();
model.RegisterContext(typeof(Models.DBDataContext), new ContextConfiguration() { ScaffoldAllTables = true });
routes.Add(new DynamicDataRoute("DD/{table}/{action}.aspx") {
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
Model = model
});
routes.MapRoute(
"Assignment",
"Assignment/{action}/{page}",
new { controller = "Assignment", action = "Index", page = "" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Admin", action = "Index", id = "" }); // Parameter defaults
}
Link that I'm trying to use is:
http://localhost:64205/DD/Work_Phases/ListDetails.aspx
I am getting the following message:
Server Error in '/' Application. The
resource cannot be found. Description:
HTTP 404. The resource you are looking
for (or one of its dependencies) could
have been removed, had its name
changed, or is temporarily
unavailable. Please review the
following URL and make sure that it is
spelled correctly.
Requested URL:
/DD/Work_Phases/ListDetails.aspx
I've tried replacing DD with DynamicData since the folder inside of the app is DynamicData and that yielded the exact same result.
The URL
http://localhost:64205/DD/Work_Phases/ListDetails.aspx
is matching your second (default) route, which is trying to hit a controller called "DD".
You may need another route entry that looks something like this:
routes.MapRoute(
"DD",
"DD/{action}/{page}",
new { controller = "NameOfController", action = "Index", page = "" }
);
...although I can't imagine why you would need to pass a page parameter. The page view that is hit depends on the return action of the controller method.
For a better look at integrating Dynamic Data with ASP.NET MVC, have a look at Scott Hanselman's Plugin-Hybrids article. He has some details about handling the .ASPX files that are not part of MVC. In particular, if you have an .ASPX that you don't want to be processed by the ASP.NET MVC controllers, you can install an Ignore Route:
routes.IgnoreRoute("{myWebForms}.aspx/{*pathInfo}");
It should be noted that ASP.NET MVC is configured out of the box to ignore URL requests for files that physically exist on the disk, although Scott's IgnoreRoute technique is apparently more efficient.
The url doesn't match your dynamic data route because it doesn't fit the constraints you put on it. You're requesting action ListDetails but only these actions are allowed
Constraints = new RouteValueDictionary(
new { action = "List|Details|Edit|Insert" }
EDIT: are you sure that an action called ListDetails exists? Then modify the constraints above to
Constraints = new RouteValueDictionary(
new { action = "ListDetails|List|Details|Edit|Insert" }
Just to be sure that it's the constraints that's causing the route to be ignored, can you try one of the default actions? E.g.
http://localhost:64205/DD/Work_Phases/List.aspx
For ASP.NET MVC to work, you will have to match the URL you are trying to access with the list of routes.
For your current global.asax, example of valid URLs are:
http://domain/AnyController/AnyAction/AnyParameter
http://domain/Assignment/
http://domain/Assignment/AnyAction/AnyParameter
MVC requests are redirected to the proper Controller class, Action method, with parameters as passed in. MVC request is not redirected to any ASPX class. This is the difference between ASP.NET MVC and vanilla ASP.NET Page.

Can two different URLs be routed to the same view in ASP.NET MVC?

I am just starting to learn ASP.NET MVC and I have a situation where I have two URLs which I would like to point to the same view.
For example I could have http://some.domain/reports/daily/team1 and http://some.domain/team1/reports/daily. Could I then point them to the same view as the request is obviously the same?
The reason I am asking this is because people are forever typing the directories in the wrong order and it would be nice to pick them up rather than dump them at the 404 page.
Yes you can. Add another one of these.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Just fill in the URL part with what you want to do or rearrange the {} parts.

Resources