I've been assigned to rewrite some existing ASP.NET pages using MVC. Prior to working on this assignment I was completely uneducated on MVC.
The pages I'm working on are simple reports that accept parameters from the user, pass the parameters to a stored procedure (SQL Server) and return a set of data which is displayed on a web page.
Prior to my arrival on this project a previous team member had been in the process of converting these pages to MVC. He left before I arrived. Now I have been assigned to continue the task of converting these pages to MVC.
I've worked through some MVC tutorials on W3schools and Channel 9, and those made sense to me. I was able to get those simple tutorial apps up and running without any trouble. But I'm having a whole lot of trouble converting these 'real' pages to MVC.
I say "converting", but what I mean by that is that I'm leaving the existing pages alone and building a new MVC "page" that mimics the behavior of the existing page.
I've been working under the assumption that I could create a new controller, then build a new view off of the new controller, then run my application and navigate to the new view by typing it's associated URL into the browser's address bar. But when I try this I get a 404 error.
No one else on my team is familiar enough with MVC to give me any kind of advice. I have no idea how to troubleshoot this situation. I'll provide as much specific information as I can about the project I'm working on, I'm just not sure what details to provide at the moment.
So in summary, what I'm asking for right now is some help on how to create a new view in this existing application and how to get the application to successfully display the view when I attempt to navigate to it's URL.
Thanks.
Edit:
I've started out with a very simple controller, just to see if I could get the application to display its associated view. The controller isn't meant to do anything other than display its associated view. Here's the code for it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TSS.Controllers
{
public class Tim_Dev_Controller : Controller.
{
//
// GET: /Tim_Dev_/
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
return View();
}
}
}
Edit 1.1:
Here's code for the corresponding view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
Edit 2:
Here's the contents of the routeconfig.cs file:
using System.Web.Mvc;
using System.Web.Routing;
using TSS.Utilities;
namespace TSS
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{instance}/{controller}.aspx/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "CTPCatalogImportEmployee",
url: "{instance}/{controller}.aspx/{action}/{empId}/{series}"
);
}
}
}
Edit 3:
Here's a little more information. I can place a break point in the existing controllers where they call
return View()
and hit those break points when I open those pages. But when I place a breakpoint at the same
return View()
call in my new controller it never gets hit. (This is when I try to navigate to my new view by entering the associated URL into the address bar of the browser. )
You should ignore the old aspx files, and keep the routes without .aspx
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{instance}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "CTPCatalogImportEmployee",
url: "{instance}/{controller}/{action}/{empId}/{series}"
);
}
Occasionally I have a tendency to overlook the obvious. I never bothered to rebuild my solution after adding the new controller and view. Once I did that the controller fired and pulled up the view without any trouble.
[sigh]
Thanks everyone, for your help.
UPDATE1
I've added RazorGenerator and etc...
After set custom tools, I've seen generated code for my razor pages.
Added this code in assembly
public class MyAreaRegistration : AreaRegistration
{
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("Dictionary_default", "MyDictionary/{Action}/", new { controller = "DictionaryControllerBase", action = "Index" });
}
public override string AreaName
{
get { return "MyDictionary"; }
}
#endregion
}
But when I open page by url /MyDictionary, i see "Unable to find the resource."
NOTE I use in my project MVC3 and Spring.Net
I use one controller (base controller) in another Assembly with razor pages.
In my project I make controller inherited from base controller, just it make some settings. But razor pages I wish to use from assembly.
How can I do it?
You could the RazorGenerator extension. I have detailed how this can be achieved in the following post. The idea is that the RazorGenerator extension would create a corresponding .cs file for each Razor view and it will update it every-time you make a change to the corresponding view. This way the Razor views will be precompiled in the class library along with their respective controllers and view models. The RazorGenerator.Mvc NuGet will then register a custom virtual path provider which will take care of resolving those views.
I want to make a new project and I want to add a new page, using the Microsoft sample website as a starting point. The Microsoft sample website already has an About and a Contact page.
How do I add a new page to the sample website using ASP.NET mvc4?
In ASP.NET MVC you work with Models, Controllers and Views. Controllers are classes containing methods called Actions. Each Action is used as an entry point for a given user request. This Action will perform any necessary processing with the model and return a view. So basically you will start with defining a Controller (if not already done) and add Actions to it:
public class HomeController: Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomeAction()
{
return View();
}
}
Then you right click on the Action name and select the Add->View option which will create a new View for the given Action in the respective ~/Views folder.
I would recommend that you start by going through the basic tutorials here: http://asp.net/mvc
I am completely new to ASP.Net MVC. I just created an MVC3 project in Visual Studio 2010. The view engine is razor. When I just ran the application it gave the proper result in the browser. The URL is http://localhost:4163/ . Then I applied “Set as Start Page” to Index.cshtml inside ~\Views\Home folder. Then when I ran the application the url became http://localhost:4148/Views/Home/Index.cshtml and it said the resource cannot be found. What do I do to correct it? Where is the url mapping done?
Global.asax file:
using System.Web.Mvc;
using System.Web.Routing;
namespace TEST
{
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.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
URL mapping or "routing" is handled by Global.asax in the root of your ASP.NET MVC site.
When you click "Set as Start Page" it changes the project settings to look for that file relative to the application root. But in MVC the default route to your index page is actually http://localhost:4163/Home/Index - read something like this to get an idea of how routing works.
To "fix" your project now that it's trying (and failing) to navigate to the view directly, right click the project and choose "Properties", click the "Web" tab and choose "Specific Page", leaving the text box blank. Now when you start to debug it should go to the home page again - look at the default route parameters to see why in the RegisterRoutes method in Global.asax
Make sure you created a HomeController.cs class in your controller folder.
In a similar issue I faced, my Action had an HTTP "POST" attribute, but I was trying to open the page (by default it's "GET").
So I had to create an HTTP "GET" version.
Unbelievably, I'd accidentally deleted the public keyword from the controller!
I imagine this will help precisely no one else, but you never know ...
I too got the same html-404 error:
The resource cannot be found.Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
But after close examination, I found that I had left the name of the controller as Default1Controller instead of changing it to HomeController. When I made the change and debugged the app it worked. Hope it will help you if you have the same problem.
Follow below steps to run you asp.net mvc application.
Controller creation
Right click on controllers folder and add controller.
Note - don't remove Controller postfix. Its ASP.NET MVC conventions.
Give name to controller as "DemoController" and you can see "Index" action is present in "DemoController". "Index" is default action present when you will create a controller.
View Creation
Right clicking on "Index" action name and keep
default view name i.e. "Index" and click on "Add" button.
Route Setting
Open Global.asax file, then you will see the default setting of route
is mapped to "Home" controller and "Index" action change it to "Demo"
controller and "Index" action. URL mapping is written in Global.asax
file. When you open Global.asax file then you will see below setting:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Change it into:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Demo", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
And run your application you can see your application in working.
Well you cannot set the default page in asp.net mvc.
Go to global.asax.cs and see the definition of routing. The default route points to Index method HomeController.
You'll better watch some short movies about asp.net mvc or try to find nerd dinner tutorial which will make you familiar with the framework pretty quickly.
I think the best answers about tutorials were already provided as answers to this question:
ASP.NET MVC Quick Tutorials
I had a similar problem some time ago when using VS 2012.
Solved by just Rebuilding the application by clicking Build > Rebuild.
In asp.net mvc you can't use option 'set as start page', because mvc views is not independent, like web forms pages. It is only template files for displaying your model. They have no processing http module. All web requests should pass through controller actions, you can't request views directly.
If you're using IIS Express. It can be that you opened another project which uses same virtual directory. When you opened 2nd solution VS remaps that IIS directory to another location. As result it won't work with different problems. I had same error as topic starter.
To fix: Close all instances of VS Studio. Open VS with project you're working & rebuild.
Just adding this one in here - if anyone is having issues where the index page on the Home Controller no longer loads, it might be because you haven't setup your StartUp Project yet. Right-click the project that you want your app to start at and set it as the startup project, and you should be good to go.
(MVC 5): Change RouteConfig.cs to include two routes like this:
routes.MapRoute(
name: "DefaultWithLanguage",
url: "{language}/{controller}/{action}/{id}",
defaults: new { language = "fa", controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new {language= "[a-z]{2}"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { language = "fa", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
so when the language part of the route is not specified it does not mistake the controller names which not match regex "[a-z]{2}" and replaces default language and redirects to rest of route...
For me the problem was caused by a namespace issue.
I had updated my project namespace in my web project classes from MyProject to MyProject.Web, but I had forgotten to update the Project Properties >> Default Namespace. Therefore when I added a new controller it was using the old namespace. All I had to do was correct the namespace in the new controller and it worked.
Simple Solution using HomeController.cs:
Open HomeController.cs file under Controllers folder.
Add the code:
public ActionResult Edit()
{
return View();
}
Now, if you are using a different controller (not HomeController):
To see your View like this:
http://localhost:1234/xyz/MyView
In the xyzController.cs file, under Controllers folder,
make sure you add an ActionResult method like this:
public ActionResult MyView()
{
return View(myView); //pass in your view if you want.
}
I also got this message when I wasn't referencing my model name correctly:
#using (Html.BeginForm("MyView", "MyModel", FormMethod.Get))
asp.net mvc project's start page is "Current Page" defaulty. Just open an server-side file and start project. in that way mvc open the default controller which is homecontroller for your project
You can change the start page inside of your project's properties (project -> project properties). Under the web tab you can select specify page and change your start page to home/ or home/index. This will direct you to the proper page according to your routes. The address of http://localhost:4148/Views/Home/Index.cshtml doesn't work specifically because it is being handled according to your routes which state that the url needs to be http://localhost:4148/{controller}/{action} and an optional /{id}.
If you want to learn more about routing take a look here.
in the address bar on browser input like this:
ControllerName/ActionMethod
not input ControllerName/ViewName
for example
in address bar: http://localhost:55029/test2/getview
cshtml file code:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MyView</title>
</head>
<body>
<div>
</div>
</body>
</html>
and cs file code:
public ActionResult GetView()
{
return View("MyView");
}
If you have tried all of the above solutions and problem still persists then use this simple solution.
Open facebook debugger from this link, type page url and click on Fetch new Scrape Information button. This will solve your problem.
The reason behind (what I think) is that facebook api saves current state of the page and shows same from its own server. if you click share button while coding and your page actually is not uploaded then facebook api could not find that page on server and saves the page state as "resource not found". Now it will keep showing same message even after you upload the page. When you fetch page from facebook debugger, it resolve everything from scratch and saves current state of the page and then your share button starts working without any change in the coding.
I had the same sort of issue, except I was not using the name Index.cshtml for my View, I made it for example LandingPage.cshtml, my problem was that the ActionResult in my Controller was not the same name as my View Name(In this case my ActionResult was called Index()) - This is actually obvious and a silly mistake from my part, but im new to MVC, so I will fail with the basics here and there.
So in my case I needed to change my ActionResult to be the same name as my View : LandingPage.cshtml
public ActionResult LandingPage()
{
ProjectDetailsViewModels PD = new ProjectDetailsViewModels();
List<ProjectDetail> PDList = new List<ProjectDetail>();
PDList = GetProductList();
PD.Projectmodel = PDList;
return View(PD);
}
I am new to MVC, so perhaps this will help someone else who is new and struggling with the same thing I did.
I had a controller named usersController , so I tried to create it the start page by changing default controller from Home to usersController like given below.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "usersController", action = "Index", id = UrlParameter.Optional }
);
}
The solution was to change controller default value to users rather than usersController
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "users", action = "Index", id = UrlParameter.Optional }
);
}
Solved the problem by right clicking on the view I wanted as the startup page After Displaying the error "The resource you are looking for cannot be found" Simply right click on your project, go to web and select Current Page. That will solve the problem
Okay, I'm pretty new to ASP.Net / MVC 2. Can anyone explain how to use the Html.ActionLink thing? I understand that the first parameter is the displayed text, but for the second one, what is the action name??
User action in the asp.net MVC framework is based around Controllers and Actions that enable you to create pages (or links) to specific sections.
For example you might want a page to edit a Product so you have a Product Controller with an Edit Action. You can then create a Html ActionLink that will direct the user to this page.
In summary the 'action' will be the ActionResult method you want to direct your user to.
<%: Html.ActionLink("Edit Product", "Edit", "Product") %>
public class ProductController : Controller
{
public ActionResult Index() // Index is your action name
{
}
public ActionResult Edit(int id) // Edit your product
{
}
}