Adding a new page to project - c#

I have an MVC project using C#.
I have been using only one view, Views/Home/Index.cshtml to do most of the stuff I need the app to do.
Today I was asked to add a new page, that will serve as an "Admin" type of page to allow some basic crud operations to a record.
I am having trouble understanding how to navigate to a page other than the Home/Index.cshtml, actualy I do not even navigate to that page in the browser, since that is the default routing, the url looks like: http://localhost:51225/Meetings/Agenda/ -- this is how I can see the Index.cshtml page.
So far what I have done, in the HomeController, I added this code below the Index View:
// GET: Home
public ActionResult Index()
{
return View();
}
//GET: Admin
public ActionResult Admin()
{
return View(); -- I right clicked, and added a new view named "Admin"
}
My folders now look:
Views
Home
Admin.cshtml
Index.cshtml
I have not changed the RouteConfig class:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
}
I can still open my app, and see the Index.cshtml when I go to:
http://localhost:51225/Meetings/Agenda
But I do not know how to access the Admin.cshtml
So far I know it is not by simply adding Admin at the end
http://localhost:51225/Meetings/Agenda/Admin
Nor
http://localhost:51225/Meetings/Agenda/Home/Admin
Nor
http://localhost:51225/Meetings/Agenda/Home/Admin.cshtml
Is it possible to ask for help in trying to learn how and what needs to chane in my solution in order to navigate to a different page that Index in the Home folder?

Add Custom route to the RegisterRoutes method in Route confige before default route:
routes.MapRoute(
name: "AgendaRoute",
url: "Meetings/Agenda/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Final RouteConfig:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "AgendaRoute",
url: "Meetings/Agenda/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Result :
http://localhost:51225/Meetings/Agenda => Index.html
http://localhost:51225/Meetings/Agenda/index => Index.html
http://localhost:51225/Meetings/Agenda/index/1 => Index.html
http://localhost:51225/Meetings/Agenda/admin => Admin.html
http://localhost:51225/Meetings/Agenda/admin/1 => Admin.html

the default routing convention of ASP.NET MVC is Controllername/Action/parameter.
Lets say for example you have a Route like Products/Create, ASP.NET will search for an Action named Create in ProductsController and the view will be Create.cshtml inside the Products directory.
I suggest you follow that convention and create an AdminController and put Index action on the controller. Which you can Access by localhost:51225/Admin/Index. For the views, the convention is it searches for a view with the same name as the action,, that is you create a folder named Admin and put Index.cshtml inside it

You can always access anything by /ControllerName/ViewName/ParametersIfNeeded. I suggest you to add a button on the navigation bar which will be visible only for admins, and so that only they can visit that page. In your case the admin View can be accessed with http://localhost:51225/Home/Admin.

Related

How to set login page as start page in mvc application?

I am using mvc application. I want to add a login page for my mvc application. I created a login.cshtml file for login form (it contains user name and password). When I run the project, it starts with the home page. I want to start with login page. How can I achieve this?
Go to App_Start folder in your solution and open RouteConfig.cs and replace this method with your code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
Hope it help you!
Do the following:
Right-click your Project within the Solution Explorer. Choose
Properties.
Select the Web tab on the left-hand side.
Under the Start Action section, define the Specific Page you would
like to default to when the application is launched.
Save your changes.
Answering because I had the same question. My code looked like this in the startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
I changed the name of the controller and index to the controller and index i wanted it to call to.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Register}/{id?}");
});
Edit:
I just saw this is for MVC3. Maybe it helps someone else.
Original:
In your global.asax file there is a default route specified in the RegisterRoutes function:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Site", action = "Index", id = UrlParameter.Optional }
);
Just change the parameters.
To keep people from entering the site without logging in you have to keep track of the user's login status, e.g. in the user session, and check it whenever an action is being called.
Go to HomeController.cs and just replace the
public ActionResult Index()
{
return View();
}
with
public ActionResult Index()
{
return View("Login");
}
For this to work, your login.cshtml should be in the Views/Home folder.
If it is inside another folder, then try this:
public ActionResult Index()
{
return View("~/Views/YourFolderName/Login.cshtml");
}

ASP.NET MVC - Routing doesn't work

I am practicing ASP.NET MVC using vs 2013, and writed a simple project, with one controller and view.
controller code:
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult ShowMyHome()
{
return View("MyHome");
}
}
"MyHome" view Code:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Hello World</title>
</head>
<body>
<div>
Welcome my first MVC page
</div>
</body>
</html>
RouteConfig code:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Home",
url: "Home",
defaults: new { controller = "Home", action = "ShowMyHome", id = UrlParameter.Optional }
);
}
}
when i run and set url line on "http://mySite/Home/ShowMyHome", it works well.
but when i run and set url line on "http://mySite/Home", i get a error:
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
It looks like the "Home" routing doesn't work.
Your Home route isn't being reached because when navigating to ~/Home the default route is matched, given that your controller name is HomeController.
If your desired result is to map ~/Home to ShowMyHome() explicitly then you will need to move your custom route above the default one.
You don't need to define a separate route for each controller actions you create, 9 times out of 10, the default route is fine.
The problem isn't routing, it's that ASP.NET can't find your Index.cshtml view. You need to add a view for Index().
You still have the default route pointing to the 'Index' view and action, which doesn't exist. Place your custom route before the default route and your problem should be solved.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Home",
url: "Home",
defaults: new { controller = "Home", action = "ShowMyHome", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
routes.MapRoute(
name: "Home",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "ShowMyHome", id =UrlParameter.Optional }
);
You will need to create a view for Index. In the Controller, right-click on Index() and choose "Add View".
Then, complete the wizard for how you want that view to behave.
Edit: Based on the answers I'm seeing, I believe there may be a small misunderstanding. You should not need to create a new route for every Controller you make. You should generally use the default route and use Index as your home page. Custom routes tend to come into play when you need to provide more information to your controller than just /action/id.

How do I set up my Routing for my MVC Page?

Greetings New to MVC ...
I am creating my first MVC Application, and I have created it as follows:
CustomUtilities/Controllers/GCItemRetrievalController.cs
CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
CustomUtilities/Views/Web.config
I want to pull up "GCRetrieve.cshtml in my browser ... but I keep getting a 404 Error
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
what am I doing wrong? I created the folders for the controllers, models, and Views in a seperate folder on the main system.
Your controller should look something like this:
public class GCItemRetrievalController : Controller
{
public ActionResult GCRetrieve()
{
return View();
}
}
When you navigate to the following url:
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
It should find the controller's GCRetrieve method and execute it. The return View() call will look for a .cshtml file named GCRetrieve.cshtml, as that is the name of the method.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
When you create a MVC application a class file named as RouteConfig.cs is created in App_Start directory. It has default routing as
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
In the above default routing:
if you want call a view CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
I think CustomUtilities is your project name then use following
http://mainsite/GCItemRetrieval/GCRetrieve
that is
[domanin]/[controllername]/[actionname]
For default routing detail you can refer to http://www.niceonecode.com/Q-A/DotNet/MVC/routing-in-mvc-4/20190

Displaying View of MVC in browser that dont have controller or action

In MVC, I have created a .cshtml file in the path "App/Main/Views".
I dont have any controller or Action for this file. But I need to display the content of .cshtml file in browser.
Please, let me know how I should give route path in 'RouteConfig.cs' file to achieve the above scenario.
Asp.Net MVC is based around Controllers that return views. Your routes point to Actions in Controllers that render Views. What you seem to be looking for is a static view which in this case can be handled as a pure *.html-file instead.
If you have no Controller or Action, it shouldn't be a view.
You can try this configuration
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Main", action = "Index", id = UrlParameter.Optional }
);
}
}
And then in your MainController return that view this way:
public class MainController : Controller
{
// GET: Main
public ActionResult Index()
{
return View("MyView", new MyViewModel{ title = "blabla"});
}
}

ASP MVC4 Finding appropriate method in controllers with the same name in different areas

I have seen some similar questions but i found that i have a diferent problem.
I have a MVC4 project with controllers in the base project and 3 areas. Each area contains a controller named AdminController and a method List.
My problem is when i use a link to go to method List always go through the same controller (e.g. AdminController in Users area) but the view returned is correct.
The structure of the project is like this:
Mimbre.Administration (web mvc4 project)
Areas
Contents
Controllers
AdminController
Models
Views
Admin
List.chtml
-ContentsAreaRegistration.cs
Logs
Controllers
AdminController
Models
Views
Admin
List.chtml
LogsAreaRegistration.cs
Users
Controllers
AdminController
Models
Views
Admin
List.chtml
UsersAreaRegistration.cs
Controllers (base project)
Views (base project)
Classes for area registration contains RegisterArea method like this (with apropiate name and namespace according to the current area):
public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
"Contents_default",
"Contents/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "Mimbre.Administration.Areas.Contents.Controllers" }
);
}
Global.asax contains method for register routes for base project
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[]{"Mimbre.Administration.Controllers"}
);
}
In index.chtml (in base project) I created links to List method of each area:
<a href="#Url.Action("List", "Admin", new { area = "Contents"})" >Contents list</a>
<a href="#Url.Action("List", "Admin", new { area = "Logs"})" >Logs list</a>
<a href="#Url.Action("List", "Admin", new { area = "Users"})" >Users list</a>
In generated html these links appear like this:
Contents list
Logs list
Users list
I think these links are correct, the problem is that any link clicked always takes me through method List in AdminController of Users area, method List in AdminController of another areas are never picked.
This problem could be solved by renaming the name of the controller, unique name for each area, but i really need keep the same controller name in all areas, any idea???
Thans in advance!!!
Finally I could simulate your problem. The only way that I could have the same output as you (doens't matter what area you're trying to access, but reaching same users controller and responding with right view) is when you register the Area with the wrong controllers namespaces.
/Admin/Home/List route:
namespace SandboxMvcApplication.Areas.Admin.Controllers
{
public class HomeController : Controller
{
public ActionResult List()
{
ViewBag.Message = "You've acessed Admin/List";
return View();
}
}
}
/Admin/Home/List view:
#{
ViewBag.Title = "List";
}
<h1>Admin</h1>
<h2>#ViewBag.Message</h2>
Admin Area Registration:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "SandboxMvcApplication.Areas.Admin.Controllers" }
);
}
/User/Home/List route:
public class HomeController : Controller
{
public ActionResult List()
{
ViewBag.Message = "You've accessed User/List";
return View();
}
}
/User/Home/List view:
#{
ViewBag.Title = "List";
}
<h1>User</h1>
<h2>#ViewBag.Message</h2>
User Area registration:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"User_default",
"User/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "SandboxMvcApplication.Areas.Admin.Controllers" }
);
}
With this configuration, my outputs are:
/Admin/Home/List
Admin
You've acessed Admin/List
/User/Home/List
User
You've acessed Admin/List
Note that the first word works fine (insuring that the right view was rendered but with wrong data comming from list action).
If I correct the user controller namespace in UserAreaRegistration ("SandboxMvcApplication.Areas.User.Controllers"), everything works fine!
Check it out if this could help you or try to explicitly put your namespaces to the right controller. You could also check if the Admins controller are with the right namespace too.
You need to append one more setting to your route registration. This will prevent the DefaultControllerFactory from searching for controller in unintended areas.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[]{"Mimbre.Administration.Controllers"}
).DataTokens["UseNamespaceFallback"] = false;

Categories

Resources