Change #RenderBody to point to different View MVC3 - c#

By default, the #RenderBody in _Layout.cshtml in an MVC3 app points to ~/Views/Home/Index.
#RenderBody()
Where is this set and how do I change it to point to ~/Views/Account/Logon? Or wherever I want. Thanks

It doesn't point to that view, it merely renders the view that it is given
Your app starts up and goes to the default action on the routing which can be found in Global.asax
You can modify that to default to /Account/LogOn if you wish
public class MvcApplication : System.Web.HttpApplication {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}

RenderBody doesn't point by default to ~/Views/Home/Index. It renders the view that was returned by the controller action that was executed. And since in your Global.asax in the routing definition the default action is configured to be Index, it is this view that is rendered.
So all you have to do is modify your routing configuration so that the default action is Logon on the Account controller:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
);
Now when you navigate to /, the LogOn action of the Account controller will be executed which itself will render the ~/Views/Account/LogOn.cshtml view.

You should use #RenderPage instead. Follow this link for more information.

Related

Adding a new page to project

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.

Make an MVC controller the default in WebAPI project

I have created my first WebAPI project to learn, which had an index.html page in the root of the project. I set that page as Startup. All working fine. But, I want to use an MVC controller to call the View instead.
So I created a new MVC controller in my Controller folder called "DefaultController". In it, there's a method:
public ActionResult Index()
{
return View();
}
I created a View folder, and off that, a Default folder, in which, I created an Index.cshtml file.
When I start the project, it calls my old index.html. So, I changed the startup to be the index.cshtml, which is wrong - know. MVC calls a controller method. So, I'm trying to work out - how do I call the controller method in my DefaultController?
I think I need to change my routes?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
My plan is to use cshtml pages (instead of html pages) to make use of layouts and allow controllers to initiate the views. Each view will the use an api call back to my WebApi controllers to do the data handling.
Does that seem like a good way to handle my WebAPI/KnockoutJs project?
I just need to know how to get the controller to be the default.
When removing the index.html page, I get the error:
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
I think you need to add the controller name to the defaults object as in:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You need to register both WebAPI routes and MVC routes:
All this should be done in Application_Start method in Global.asax.cs file:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
GlobalConfiguration.Configure(WebApiConfig.Register) is used to configure WebApi (and register api related routes)():
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
RouteConfig.RegisterRoutes(RouteTable.Routes); is used to register MVC routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You also need verify that the DefaultController that you created is MVC controller (inherits from System.Web.Mvc.Controller) and not WebAPI controller
According to my experience, when you want to call the index.cshtml, in the route config you have to define the controller like this in the RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The controller supposed to be "Home", and the Action is "Index". But, this maproute is for default one. How about if you want to add another one?
routes.MapRoute(
"Article",
"articles",
new { controller = "News", action = "ArticleList" }
);
You can write freely as shown above where "Articles" is the name of maproute and the "articles" is the url. And it would become like this (http://www.domain.com/articles) if you compile controller News and Action ArticleList. And "..../articles" is something you replace (No need define controller or action) and you don't need to open www.domain.com/News/ArticleList it's enough to go to url www.domain.com/articles and the maproute would be automaticaly route to controller news and action articlelist.
That's only my point of view about how maproute works.
CMIIW :)

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

How to make login page a startup page in ASP.NET MVC web application?

I want to make a login page that opens when I start up the ASP.NET MVC web application. I also want to automatically redirected the user to the Home/Index page after a successful login.
Furthermore the login page has a Register button which is redirected to the register page, I want the register page to be redirected to the Home/Index after successful registration.
You do not want to make Login as home page. It is not a good design. Mainly because after a user login and enters https://yoursite.com in browser, you do not want to display Login page again.
Instead, you just need to apply [Authorize] to home controller.
[Authorize]
public class HomeController : BaseController
{
// ...
}
Or Global Filter
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
}
If a user access your home page, s/he will be redirected to Login Page first with ReturnUrl in QueryString.
For example, https://yoursite/Account/Login?ReturnUrl=%2f
Make sure you set your login page in loginUrl in web.config.
<system.web>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"/>
</authentication>
</system.web>
You have two options:
1. Register a default route to your login page
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Login"}
);
}
Make Home/Index requiring Authorized access, this way you will make sure that if logged in user is accessing your site he goes straight to authenticated page than login
Routing is the best option for it.You can set your default page by make changes in your config file.You will find there are two config files :
1.app.config
2.route.config
By using Route Config you can rewrite your url as well :-
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
}
);
}
}
Note that any MVC application must have at least one route definition in order to function. In the above, a route template named "Default" is added to the routes collection. The items in curly braces enclose Route Parameters, and are represented by the parameter name as a placeholder between the curly braces. Route Segments are separated by forward slashes (much like a standard URL). Notice how the implied relative URL our route specifies matches the MVC convention:
~/{controller}/{action}
You can chane the url as well in the following way:-
routes.MapRoute(
name: "SiteMap",
url: "sitemap",
defaults: new { controller = "Static", action = "SiteMap", id = UrlParameter.Optional },
namespaces: new string[] { "name.Web.Controllers" }
);
For setting a default page:-
the best way is to change your route. The default route (defined in your App_Start) sets /Home/Index
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
as the default landing page. You can change that to be any route you wish.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "Sales", action = "ProjectionReport",
id = UrlParameter.Optional }
);
Hope you got a clear idea about it

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"});
}
}

Categories

Resources