adding custom view name in asp.net mvc4 - c#

I am building an application in .net mvc4 that is based on business promotion and sales store.
User on this web application would be able to use product and access his/her personal business page also, that page can be promoted in future.
So I added one controller- Mypanel and a view of user's personal or professional business page _Mypanel.
Now the url access to this page is Bizcopter.com/Mypanel/_Mypanel
I want a custom user defined page name-
i.e. If a business name is - BookStore
Then I want to add a view in this same controller with the name of BookStore, So URL of personal business page would be-
Bizcopter.com/Mypanel/BookStore/ and this business holder can promote his business page with this URL.
Let me know if these are possible-
Replacing the view's name of user's choice
Add a view from client side in this same controller
I don't have any idea how to make it happen so don't have any trying code.
Site URL- http://bizcopter.com/Mypanel/_Mypanel

You don't need a separate view and controller action for each business.
I would create a controller and view called MyPanel. The controller takes a parameter called something like businessName that will load data related to the parameter.

By default you'll have a route in your AppStart/RouteConfig.cs which may look like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
The default URL structure might look something similar to: http://localhost:{PortNumber}/{Controller}/{Action}
Where we can attribute the following:
Controller = Home
Action = Index
Now if you want something similar to how you have it, you'd want something along the lines of:
http://testing.com/Fruits/Apples
Controller = Fruits
Action = Apples
By default, a URL pattern will match any URL that has the correct number of segments, in this case {controller}/{action}
Overall you should just need the MyPanel controller, and a controller taking a parameter of string which loads the correct Object/Model into the view.
Source: Pro ASP.NET MVC 4 - Adam Freeman

As the others said you can add a new route.Consider this code:
routes.MapRoute(
name: "MyCustomRoute",
url: "MyPanel/{name}"
defaults: new { controller = "MyPanel", action = "MyAction", name="" }
);
In this route if user type this URL:
Bizcopter.com/Mypanel/
Then it goes to your MyAction in your MyPanel Controller by default.Actually it will always go to MyAction, and in your MyAction, you must take the name parameter and redirect to user to the Relevant Action like this:
public ActionResult MyAction()
{
var name = RouteDate.Values["name"];
// check the name and redirect user to another action if it necessary
if(name == "BookStore") return RedirectToAction("BookStore","Mypanel");
}

Related

How to MapRoute to a sub controller

I have a file, AdminController.cs, that currently holds the controllers for every action in the admin section of my site. Obviously, this is getting huge, and I'd like to delegate control to a different controller for each application.
For instance:
www.mysite.com/Admin/Car currently looks to AdminController.cs to decide what to do. So when a user adds a car, there is an ActionResult in AdminController.cs called AddCar(). I would like this instead to look to CarController.cs to find AddCar().
So I after some research, I added this to my RouteConfig file:
routes.MapRoute(
name: "/Admin/Car"
url: "{parent}/{controller}/{action}",
defaults: new { parent = "Admin", action = "Index" },
constraints: new { controller = "Car"}
);
I commented out the ActionResults related to 'Car' in AdminController, and added them to CarController.
However, I'm getting "The resource cannot be found." when I navigate to www.mysite.com/Admin/Car.
How can I use a different controller, but with the URL still in the Admin realm?
You could add a controller action 'Car' to the Admin controller which redirects to the relevant action in the Car controller. But, Areas are probably what you want.

How can I route requests to a page controller for routes that don't exists in ASP.NET MVC 4

How can I route requests to a default PageController for routes that do not map to a controller or action? But for routes that do match a controller or action, have those behave as normal, using ASP.NET MVC?
Basically I have a CMS backend that I have developed and I need to be able to inspect the route, to see if it matches a route for a page, stored in the database and if so, forward the request to the default PageController, which handles loading the pages content from the database. There are also CORE pages, that do have their own Controllers and Actions defined, and if you enter a route that doesn't match a pages route in the database, I need it to revert to the default behavior of ASP.NET MVC and look for the {controller}/{action}.
I have searched and searched online, with not much luck finding how I could do this. Any help would be greatly appreciated.
Set your routes up so the ones for existing controllers and actions are first, then have a catchall that maps to your PageController:
// More specific routes go here
routes.MapRoute(
null,
"{controller}/{action}/{id}", // URL with parameters
new { action = "Index", id = UrlParameter.Optional }, // Don't put a default for controller here
// You need to constrain this rule to all of your controllers, so replace "ControllerA" with an actual controller name, etc
new { controller = "ControllerA|ControllerB|ControllerC" }
);
routes.MapRoute(
null,
"{*path}",
new { controller = "Page", action = "Index" }
);
Anything that isn't matched by the first rule and any rules you put before it will fall back to your page controller, with the path in a path parameter on your index action method.

Is there a way to make the route mapping based on specific path

I code lots of ASP.NET but I'm kind of new with .net MVC, I've a default route registered like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
And I want to add another Administrator area on the site and all the URL would be something like "http://localhost/Administrator/controller1", "http://localhost/Administrator/controller2", etc. I've lot of controllers in the Administrator namespace and I'm trying to register those controller with only one MapRoute, I did something like this:
routes.MapRoute("Administrator_default", "Administrator/{controller}/{action}/{id}", new { controller = "Administrator", action = "Index", id = "" });
it works with those controller but one problem is that in some other controller while I try to do a redirect like:
return RedirectToAction("Index", "Forum");
Then I'll always be redirect to http://localhost/Administrator/Forum instead of http://localhost/Forum, it's not a big issue but make the URL looks strange, I tried to restrict to certain namespace but it's not working. It looks just as I'm trying to register two default route and .Net just match the first one, I'm wondering is there a way to make it two default route and map on only specific path only?
This exact issue is why Areas were added to MVC 2. http://www.asp.net/whitepapers/what-is-new-in-aspnet-mvc#_TOC3_2
Agree with Zach's answer.
Not ideal, but you do have the option to have controllers in the controller root folder (e.g. /controllers/HomeController.cs) of your project as well as the controllers in Areas (maybe high level root pages that display menus for areas).
Secondly a quick tip on using the RedirectToAction method. You can specify the area you would like to redirect too using the route parameters e.g:
RedirectToAction("Index","Form", new { area = "MyOtherArea" });

Understanding routing in ASP.NET MVC

I'm trying to wrap my mind around the way ASP.NET MVC implements routing.
From what is my current understanding, it seems my route string much have a "{controller}" and "{action}", otherwise it doesn't work?
How would I define the route that using a SearchController and Search action taking both SearchKeywords and SearchCaseSensitive arguments had the following URL?
domain/SearchKeywords/CaseSensitive
Even simpler, how do I map domain to controller SearchController and to Search?
From what is my current understanding,
it seems my route string much have a
"{controller}" and "{action}",
otherwise it doesn't work?
Values for the controller and action tokens are required. You have 2 options for providing the values:
1) Using {controller} and {action} tokens on the URL template. e.g.:
routes.MapRoute(null, "{controller}/{action}");
2) Using default values for controller and action. e.g.:
routes.MapRoute(null, "some-url",
new { controller = "Search", action = "Search" }
);
How would I define the route that
using a SearchController and Search
action taking both SearchKeywords and
SearchCaseSensitive arguments had the
following URL?
domain/SearchKeywords/CaseSensitive
The URL host (or domain) is not considered by the routing system, only the application relative path. You can do this:
routes.MapRoute(null, "{SearchKeywords}/{CaseSensitive}",
new { controller = "Search", action = "Search" }
);
You can also provide defaults for SearchKeywords and CaseSensitive, if you want to make either of them optional.
You can add controller = "Search", action = "Search" to the defaults (the last parameter).
The routing engine will use values in defaults to fill in for parameters that aren't in the URL.
If you want to have a 'domain' parameter in your route, you must put this at the top of the route registration. The 'domain' parameter in the second anonymous object is a constraint and here is set to be a regular expression that tests to see if the domain is either of the possible domains "DefaultDomain" or "OtherDomain".
routes.MapRoute("DomainRoute", "{domain}/{controller}/{action}",
new {domain = "DefaultDomain", controller = "Search", action = "Search"},
new {domain = "DefaultDomain|OtherDomain"});

mvc.net dynamic urls

I am looking to produce an MVC site which has complete control of the url structure using routing.
routes.MapRoute(
"BlogView", // Route name
"view/{blogurl}", // URL with parameters
new { controller = "view", action = "view", productLink = ""} // Parameter defaults
);
routes.MapRoute(
"ProductGrid", // Route name
"category/{category}", // URL with parameters
new { controller = "category", action = "Index", category = "" } // Parameter defaults
);
I currently have the follwoing urls;
www.myblog.com/view/first-post
www.myblog.com/view/another-post
www.myblog.com/category/code
www.myblog.com/category/example
The first two urls relate to the detail view, the latter two relating ot a category view.
I have a database with the following structure; I ensure that the url (chrUrl) is a unique key.
url ( idurl (int),
chrURL,
chrAction,
chrController
)
My plan is that it is possible to look up rewrite the route lookup table so that the follwoing urls redirect to the correct view and page in the site;
www.myblog.com/first-post
www.myblog.com/another-post
www.myblog.com/code
www.myblog.com/example
Is this possible? Perofmance aside, is there a problem with this and how shoudl I go about this?
Since you don't have anything to differentiate between view and category items, I'd think about using a default controller which checks if the id is in the categories table and passes control to either the View or the Category controller.
routes.MapRoute(
"Root", // Route name
"/{id}", // URL with parameters
new { controller = "default", action = "redirect"} // Parameter defaults
);
But if you can live with having "/category/" in your category urls, that will be the more elegant solution on the back end.
First up, I would suggest coming up with a URL scheme that you are happy with. (seems you have one already)
Then I would use a ControllerFactory that will be responsible of Instantiating and
running the right action on the right controller. That is independent of any routes that you define in your route table - in fact it wont matter what you have there since you want your URL to be "database driven". You invoke the controller factory from your Global.asax file :
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new Controllers.ControllerFactory());
}
Then in the GetControllerType method in your ControllerFactory, you inspect the URL with
RequestContext.RouteData.Values.ContainsKey("keyname")
to work out the url scheme the user is presenting, and do a database look-up based on that.
If you want to take this one step further, your database can also contain references to the controller to instantiate, but that would be an overkill in your situation. As a quicknote, we use that in a solution where it was important to provide the ability for non-developers to create templates without involving dev - the database held url schemes, controller and views to render on that controller.
While you are at it, if you want to make things more elegant, create a BaseController that your controllers inherit from, and in there set things in your ViewData such as your SEO tags (MetaDescription, Title, etc) - look these up from your database.

Categories

Resources