how to create hierarchy of pages in asp.net MVC - asp.net-mvc

I am working on a classified website that will have links like "electronics/mobiles/samsung/samsungS3/adTitle". How to create hierarchy of views like that in asp.net. If the answer is HMVC then please refer some link that contains complete guide how to implement HMVC.

You don't need hierarchy of Views, you should use Route Config that will allow you to get View that you need base on URL.
From 4 Version of MVC also have areas not only controlles and View by default. So check this tutorial to know how to customise your Routing.

You don't need to create views in this hierarchy but you need to create URLs in this fashion and that is called friendly URLs.
Look at following stack overflow question
How can I create a friendly URL in ASP.NET MVC? and Friendly URL
You will be defining another route which will end up on your single action method. So You will add a route in routeConfig.cs as follows
routes.MapRoute(
name: "custom",
url: "{category}/{type}/{manufacturer}/{version}/{Title}",
defaults: new { controller = "Home", action = "customRoute"}
);
and your custom action will have all values passed in as param be as follows
public string customRoute(string category, string type, string manufacturer, string version, string Title)
{
return category + type + manufacturer + version + Title;
}
You can achieve the same using action based routing as well
// eg: electronics/mobiles/samsung/samsungS3/adTitle
[Route("{category}/{type}/{manufacturer}/{Title}")]
public ActionResult Index(string cateogry, string type,string manfacture, string Title) { ... }

Related

MVC 4 routing to a controller

I am new to MVC and I am trying to mess around by creating a practice site which will be a gallery site for viewing and uploading images. The problem I encountered is that I cannot get the routing to work correctly.
Here is a link to my routing code and solution tree:
https://imgur.com/a/Oc1Tt?
Did I set the views and controller up incorrectly?
The error I get is: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
Thanks for any input
Routing works by converting an incoming request to route values or by using route values to generate a URL. The route values are either set as parameters in the URL itself, as default values, or both (in which the defaults make the URL parameters optional).
You have not set any route values in your route. Since you don't have route parameters in the URL, you need to set defaults (controller and action are required by MVC).
routes.MapRoute(
name: "Gallery",
url: "Gallery/Index",
defaults: new { controller = "Gallery", action = "Index" }
);
That said, your Default route already covers this URL. You only need to add custom routes if you desire behavior that the Default route doesn't cover.
Also, if you change the view names so they don't match the name of the action method, you have to specify the name explicitly from the action method.
public ActionResult Index()
{
return View("~/Views/Gallery/GalleryView.cshtml");
}
By default MVC uses conventions. It is much simpler just to name the view Index.cshtml instead of GalleryView.cshtml so you can just return View from the action method.
public ActionResult Index()
{
return View();
}

How do I make friendy URLs in ASP.NET MVC with all products in the root?

I'm in the process of building a web shop in ASP.NET MVC. What I would like to accomplish is a list of all the products in the root of the web shop. In other words I would like a SEO optimized friendly URL with the names of the products directly after the base URL. For example:
myexamplewebshop.com/beautiful-red-coat
myexamplewebshop.com/yellow-t-shirt
If you click on one of these links, you will see the details page of the product. I guess I need to change something in the routing code somewhere to make this work. Can anyone give me an example of how to accomplish this? Any help would be greatly appreciated.
Add a route like:
routes.MapRoute(
"SEO_Product", // Route name
"{seoterm}",
new { controller = "Product", action = "LookupBySEO" }
);
Then in your Product Controller add method:
public ActionResult LookupBySEO(string seoterm) {
// convert URL encoded seoterm into product name
// lookup product by name
}
This route should be added before the default route.
NOTE: Every other page on your site cannot be on the root level anymore, i.e. /aboutus, /home, etc.
You would need to add a custom route to your RegisterRoutes function.
routes.MapRoute(
"ProductFriendly", // Route name
"{productId}", // URL with parameters
new { controller = "YourProductControllerName", action = "YourProductActionName" } // Parameter defaults
);
Would map to an action in a YourProductControllerName called YourProductActionName
public ActionResult YourProductActionName(string productId)
{
// your code goes here...
}

ASP.NET MVC Dynamic Action with Hyphens

I am working on an ASP.NET MVC project. I need to be able to map a route such as this:
http://www.mysite.com/Products/Tennis-Shoes
Where the "Action" part of the URL (Tennis-Shoes") could be one of a list of possibilities. I do not want to have to create a separate Action method in my controller for each. I want to map them all to one Action method and I will handle the View that is displayed from there.
I have this working fine by adding a route mapping. However, there are some "Actions" that will need to have a hyphen in them. ASP.NET MVC routing is trying to parse that hyphen before I can send it to my action. I have tried to create my own custom Route Handler, but it's never even called. Once I had a hyphen, all routes are ignored, even my custom one.
Any suggestions? Details about the hyphen situation? Thanks you.
Looking at the URL and reading your description, Tennis-Shoes in your example doesn't sound like it should be an action, but a Route parameter. Let's say we have the following controller
public class ProductsController : Controller
{
public ActionResult Details(string product)
{
// do something interesting based on product...
return View(product);
}
}
The Details action is going to handle any URLs along the lines of
http://www.mysite.com/Products/{product}
using the following route
routes.MapRoute(
null,
"Products/{product}",
new
{
controller = "Products",
action = "Details"
});
You might decide to use a different View based on the product string, but this is just a basic example.

How do I do Short URLs in MVC?

Suppose I want to publish (like in paper catalogs) some "short URLs" that are easy to type/remember, but I want them to redirect to a verbose, SEO-friendly URL. How do I accomplish that with MVC routes?
Example:
http://mysite.com/disney
becomes
http://mysite.com/travel/planning-your-disney-vacation (with "travel" as the Controller)
The things I've tried:
Just setup a route for it. Problem: the URL doesn't change in the browser (it stays "/disney".
Use NuGet package RouteMagic (see Haacked's article). Problem: I get an error: The RouteData must contain an item named 'controller' with a non-empty string value. I think this is because I don't have a static word before my controller ("travel") like he did (with "foo" and "bar")???
Use a redirect module (like Ian Mercer's). Problem: the route matches on my HTML.ActionLinks when creating URLs which I don't want (Haacked mentions this in his article and says that's why he has GetVirtualPath return NULL ...?)
I'm out of ideas, so any would be appreciated!
Thanks!
You could set up a catch-all type route, to direct all /something requests to a specific action and controller, something like:
routes.MapRoute(
"ShortUrls",
"{name}",
new {controller = "ShortUrl", action = "Index", name = UrlParameter.Optional}
);
(depending on how the rest of your routing is set up, you probably don't want to do it exactly like this as it will likely cause you some serious routing headaches - but this works here for the sake of simplicity)
Then just have your action redirect to the desired URL, based on the specified value:
public class ShortUrlController : Controller
{
//
// GET: /ShortUrl/
public ActionResult Index(string name)
{
var urls = new Dictionary<string, string>();
urls.Add("disney", "http://mysite.com/travel/planning-your-disney-vacation");
urls.Add("scuba", "http://mysite.com/travel/planning-your-scuba-vacation");
return Redirect(urls[name]);
}
}
I just faced the same problem.
In my Global:
routes.MapRoute(
"ShortUrls",
"{name}",
new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
In my Home Controller:
public ActionResult Index(string name)
{
return View(name);
}
This way is dynamic, didn't want to have to recompile every time I needed to add a new page.
To shorten a URL you should use URL rewriting technique.
Some tutorials on subject:
url-rewriting-with-urlrewriternet
url-routing-with-asp-net-4
URL rewriting in .Net

ASPNET MVC3: how to transform an anchor to Html.ActionLink?

I have the following a href link:
title
That i use for showing SEO-friendly urls; i would like, instead of the anchor tag, to use the Html.ActionLink.
How can i transform the anchor in ActionLink considering that i have not the Action name on the url?
You can use Html.ActionLink even when the action is not present in the URL; you just need an appropriate route. Routes are used for both inbound URL matching and outbound URL generation.
First things first, you'll need a route in the Routes collection to be used as a template for the URLs that you want to generate
routes.MapRoute(
null, // name
"News/{id}/{title}", // URL pattern
new { controller = "News", action = "Index" }, // defaults
new { id = "\d+", title = #"[\w\-]*" }); // constraints
This route will only match if id is a number and title contains only word characters and/or hyphens. The route needs to be registered before any more "general" routes as the order of routes is important; the framework stops on the first matching route, it does not try to find a "best" match.
Now you can use Html.ActionLink to generate routes.
#Html.ActionLink("title", "Index", "News", new { id = item.id, title = item.NewsSeoTitle })
You may also want to look at T4MVC (available as a NuGet package) too as it adds some overloads that removes the need for magic strings all over the place
Assuming your controller action looks like
public class NewsController
{
public ActionResult Index(int id, string title)
{
return View();
}
}
T4MVC adds an overload that allows you to use Html.ActionLink like
#Html.ActionLink("title", MVC.News.Index(item.id, item.NewsSeoTitle))
much neater :)
If you are using the custom links which is not corresponding to the controller/action structure, maybe it's better to use your own html extension
public static string SeoLink(this HtmlHelper helper, string itemId, string title, string seoTitle)
{
return String.Format("{1}",
VirtualPathUtility.ToAbsolute(String.Format("~/News/{0}/{1}", itemId, seoTitle)),
title);
}
As for Html.ActionLink: from the name of extension you can find the it work with actions. Of course you can provide such action and controller names to fit your requirements, but it's not a good idea, especially if your code will be supported by any other developer - he will never find such action in controller which is specified in ActionLink as actionName param.

Resources