I am using ASP.NET with VSCode. I am new to ASP and this is my first project. I created the project and created a folder called admin
with an index.cshtml
file in it. But when I try to access the file in the browser by typing localhost:5000/admin/
, localhost:5000/admin/index
and localhost:5000/admin/index.cshtml
, but none of these URLs display the WebPage. Instead the browser shows that the URL could not be found in localhost:5000.
I tried to find out a solution by Googling, but found nothing. I do not want to jump into MVC just yet, as I have never worked with it.
PS: Please don't get this removed with the reason that "This question needs more research." I am a beginner and have already explained what I could have.
CodePudding user response:
The way Asp.net MVC framework works is:
- Request first goes to an action and not a view (e.g.
index.cshtml
). Of course a lot happens before that - Folder name is by default mapped with the name of an existing controller. So you need to have a controller named
AdminController
that will have to be inherited from aMicrosoft.AspNetCore.Mvc.Controller
- In the
admincontroller
controller you need to have an action calledIndex
- Then your
index.cshtml
needs to be put either in the/Views/Admin/index.cshtml
location or in the/Views/Shared/index.cshtml
location
After that when you hit the Url localhost:5000/admin/index
the request will go to the Action called Index
in the AdminController
controller. The last line of an action method is usually return View();
which will look for a cshtml page named that matches the name of the action. Which is Index
in this case. So it will start to look for a index.cshtml
file. That is how it will render your index.cshtml
view if it is found.
Here a simple controller and action:
public class AdminController : Controller
{
public AdminController()
{
}
public IActionResult Index()
{
return View();
}
}
CodePudding user response:
Conventional routing typically used with controllers and views.You must create your views in the right location.In general, if you want to return a view for a controller action, then you need to create a subfolder in the Views folder with the same name as your controller. Within the subfolder, you must create a view with the same name as the controller action.
You can refer to the doc to understand what is mvc.
If you are using ASP.NET,you can try to create a AdminController in Controllers folder like this:
public class AdminController : Controller
{
public ActionResult Index()
{
return View();
}
}
If you are using ASP.NET Core MVC,you can try to create a AdminController in Controllers folder like this:
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}