MVC Changing a URL route - c#

I just watched the Pluralsight video on URL routing in ASP.NET MVC 3. I'm still a bit confused.
That image shows how my views are set up. I have a controller for each view. Perhaps I misunderstood something but when I did this I thought by adding the Portfolio view and controller instead of going to /home/portfolio it would just take me to /portfolio but it didn't. Now when I click on the portfolio link it takes me to /portfolio/portfolio.
Am I misunderstanding something about the way routing works in ASP.NET or am I just forgetting something?

It takes you to Portfolio/Portfolio because that is how you named the setup. The first one is the name of your controller (without controller in the name) PortfolioController. The second one is the name of your ActionResult, Portfolio which returns Portfolio.cshtml. If you wish to only see /Portfolio you could always have the PortfolioController use
public ActionResult Index(){ return View(); }
and then rename Portfolio.cshtml to Index.cshtml and you should be good to go.

when you have localhost/portfolio you that will call default action of portfolio which will be Index by default and you will see that view ,since you don't have view for that and you can make one
you can access your portfolio action in your portfolio controller by /portfolio/portfolio
because it follows the default route which is in routConfig.cs in app_start folder
if you want to get the same result for /portfolio/portfolio just with /portfolio you can add a route like this in your routeconfig
routes.MapRoute(
name: "portfolio",
url: "portfolio/{action}",
defaults: new { Controller = "portfolio", Action = "portfolio" }
);
be careful to write that before default route,because when it match the first route it would not check for other
sorry my English is not good

Rename the action and view to Index.

Related

ASP MVC Route Default Configuration

I'm new to ASP MVC programming and wanna ask about how the route is configured.
For example I have the Home Controller
public ActionResult Home(){
return View("Index")
}
This will find the Index.cshtml under /Views/Home/
However if I rename the Home Folder to Homees for example, the view is not found and also I try to return View with View("~/Views/Homees/Index.cshtml") this is not change that the controller not found the view.
Is this the default of the asp mvc? and it's possible to change this one?
There are few points.
ASP.net MVC is convention based. It is also specified by #Petar Minev. When it comes to search for view it use following method. It take controller name as directory name and view name file name with different extention ( like cshtml, vbhtml , aspx ) based on view engine. ( As you are using cshtml it seems that you are using both Razor and Webform view engine).
For search it will first go to directory with controller name and search for specified view. If it is not available there then it goes to shared folder.
Above is default behavior of ASP.net MVC.
Now you change folder name then first solution you have tried that must work as it works for me. ( Please check that your folder name is correct. Make sure you did not rename for area directory).
public ActionResult Home(){
return View("~/Views/Homees/Index.cshtml")
}
Another solution is to rename controller with HomeesController ( So it will automatically locate correct directory)
If you continue with this convention for other folder like the way you add "es" in "Home" it is better to add this convention in default search for view.
( You can do this by either inherit from default RazorViewEngine or change RazorViewEngine parameter)
For example
protected void Application_Start()
{
RazorViewEngine engine = (RazorViewEngine)ViewEngines.Engines[1];
List<string> currentFormats = engine.ViewLocationFormats.ToList();
currentFormats.Insert(0,"~/Views/{1}es/{0}.cshtml");
engine.ViewLocationFormats = currentFormats.ToArray();
... Other application start code
}
Razor View engine is default view engine for ASP.Net MVC. This Razor view engine is configured to locate path at specified path i.e. "~/Views/{1}/{0}.cshtml".
Here {1} placeholder specifies controller name and {0} represents view name.
Say, for Example any request for Index action in Home controller will look for view at "~/Views/Home/Index.cshtml".
Now if you want to change this default path then you have to define custom view engine. Here a sample example how can you define a custom view engine and change the default path.
public class MyCustomViewEngine : RazorViewEngine
{
public MyCustomViewEngine()
{
ViewLocationFormats = new string[] {
"~/MyViews/{1}/{0}.cshtml",
"~/MyViews/Shared/{0}.cshtml" };
MasterLocationFormats = new string[] {
"~/MyViews/{1}/{0}.cshtml",
"~/MyViews/Shared/{0}.cshtml"};
PartialViewLocationFormats = new string[] {
"~/MyViews/{1}/{0}.cshtml",
"~/MyViews/Shared/{0}.cshtml"};
FileExtensions = new string[] { "cshtml" };
}
}
You also need to register custom view engine with ASP.Net run time at Application _Start() event.
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyCustomViewEngine());
Your controller code is seems wrong, if your controller name is Home then code will be like this with index action
public class HomeController : Controller
{
public ActionResult Index()
{
return View("~/Views/Homees/index.cshtml");
}
public ActionResult Contact()
{
return View();
}
}
you just used the controller name as action name, by default in view folder there is a separate folder for each controller like for Home controller there will be a folder named Home, and inside that there will be separate cshtml file for each action result, like for my code there is a two action result name Index and Contact so under Home folder there will be two separate cshtml for both as index.cshtml and contact.cshtml. So when we request index action it will go for index.cshtml and for Contact action contact.cshtml by default, but we can spacify our own view for any action like my index view, and it works fine, your approach was correct but only problem was the Controller name and action name I think, try this way it may help
by default Microsoft's ASP.NET MVC is created over one Folder Convention which means that all files that will be Controllers should be under Controller folder, each file which will be View should be under View folder,
also if you create Mvc Route for example MyProfile, in the MVC you'll get contorller with this name and folder under the view's.
All this is controlled by the default routing which is knowing where to find, Views and controllers, so if you want to make some changes or modifications you should go to ASP.NET web site and look some tutorials for MVC Routing
Hope i helped :)
Simple just go to App_Start and Open RouteConfig.cs File and change route controller "Home" to "Homees" by default it set as "Home". If you rename your HomeController to "HomeesController" you should change to rountconfig by default route. check below image
After that open "HomeesController" from Controller folder here you can add action for view
public ActionResult Index()
{
return View();
}
and Add Action to View "Homees" Folder

Asp.net MVC Index page without domain paths

I believe this should have been asked and answered somewhere already, or is just a very basic thing, but I did not manage to find anything at all, I am guessing I might be querying my search wrong.
Either way, what I want is to display Index page without any domain paths.
What I want:
http://localhost:50024/
How I was able to make it with domain paths:
http://localhost:50024/Home/Index
I made a HomeController.cs and added a GET method for the Index view... which is in the Home folder under Views folder, and of course that creates domain paths. I do not care if I have to make extra controller or something, I just want it to display my index page without any paths. Thanks in advance!
You must set default values for the parameters in the route configuration in global.asax, similar to this:
routes.MapRoute( "Default", // Route nameĀ 
"{controller}/{action}/{id}", // URL with parametersĀ 
new { controller = "Home", action = "Index", id = "" } // Parameter defaults );
So that when the route parameters are missing, the routing system points the request to the desired controller and action.
just tested myself so i know it works
Test
obviously replace with what you have for the defaults in your routing if you have modified them or something
If all you're after is the "root" URL, you can also use ~/, like so:
Home
The Razor engine is smart enough to parse that URL in place, without needing to use the UrlHelper class.

C# View page URL

I've created a controller, called ClientController.cs and VS automatically created the necessary View files in /Views/Client. But I wanted to get these pages in a different URL... So, it is /Client but I need it at /admin/client.
What should I change?
Thank you!
It's not clear what your functionality will be in the long run, but here are a few options that allow you to get the URL format you want:
Perhaps you want a controller called "Admin" and an action called "Client". This would give you a path of /Admin/Client by default
Alternatively, you can change your route maps. For example, the following with route /Admin/Client to the Index of your Client controller:
routes.MapRoute(
"Default", // Route name
"Admin/Client/{action}", // URL with parameters
new { controller = "Client", action = "Index" } // Parameter defaults
);
Or maybe even go a far as using "Areas", depending on what you need. Have a Google of that if you're interested in learning more
If you want it to be admin/client, then using the default routing you should create an Admin Controller with an ActionResult method called Client. Your views folder should have an admin folder with your client view inside.
I haven't done a lot of MVC but i believe this is what you do.

MVC4 Multiple Controllers

This is a very basic question, yet I cannot find any clear, simple, direct answers.
I have a basic MVC4 app with 1 HomeController.cs file. I want to create a second Controller.cs file to put more code into so HomeController doesn't turn into spaghetti code.
So obviously step 1 is to add a new controller. I assume the next step is to add some stuff to RouteConfig.cs.
What do I need to add to RouteConfig.cs to utilize a new Controller.cs?
You shouldn't need to add anything. HomeController requires a line of code in your RouteConfig to be set as the default controller (for when users navigate to the site root), but any other controller should be accessible with the default routing.
Just create a controller, add some actions, and you should be able to route to it with the format Controller/Action or using the routing helper functions.
What does your routes file look like?
Normally, there's a default route:
routes.MapRoute("default",
"{controller}/{action}/{id}",
new { controller = "Home", action="Index" }
);
That means that so long as you add a new controller with the Controller suffix, MVC will make sure the routing engine sees your controller, and as long as your URL follows the above structure, requests made in that format will be routed to the appropriate controller.
We normally send it to a different view which submits to different controllers, or add a reference in your current controller if your just wanting to call certain methods in your current home controller.
What you really need first after creating a new controller is to add a new action (if it's not added automatically) and then add a new View for your new action.
You need to touch your routes only if you are about to process some specific parameters which dont match your default settings

ASP.NET MVC: Simply can't seem to get any output. help!

In Visual Web Developer when I "run" my Controller (TestApp) I come up with this:
http://postimage.org/image/iggcs6hw/
I've tried adding "/TestApp" on the end of the local host address in the address bar and that gave me this result:
http://postimage.org/image/ih078cf8/
I don't think I've misspelled anything. Forgive me if this question is a stupid one, just trying to get my feet off the ground :D.
Make sure you have renamed the default ~/Views/Home folder that was generated when you created your project into ~/Views/TestApp folder. As far as the first error message is concerned make sure you have modified the default routes in Global.asax to make the TestApp controller the default one instead of Home:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "TestApp", action = "Index", id = UrlParameter.Optional }
);
So to sum up:
Make sure that you have an Index.aspx view inside the ~/Views/TestApp folder.
Make sure that you have set the TestApp controller in the default route in Global.asax
Make sure that your TestApp controller has an Index action
Now you will be able to call your application like this: http://example.com/ which will automatically call the Index action on TestApp controller which will render the ~/Views/TestApp/Index.aspx view.
Make sure your views are in the /Views directory. MVC follows a strict folder structure and this happens when it can't find something.
When adding a new view or controller to an MVC project, it's best to use the wizard provided for that purpose.

Categories

Resources