ASP.Net MVC – Resource Cannot be found error - asp.net

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

Related

In ASP.NET MVC, how can I open a static .html page in a new tab from an action method in a controller?

I am adding static help pages to my MVC application.
Clicking the help link directs to an Action Method with a unique identifier, telling the controller which page to show.
I know it can be done from within the View using Javascript or an anchor tag.
You can also open the static page from the controller, but it does not open in a new tab:
var result = new FilePathResult("~/Help/index.html", "text/html");
return result;
I cannot seem to open this static page in a new tab from the controller. Is this even possible?
EDIT
As to why How do you request static .html files under the ~/Views folder in ASP.NET MVC? does not solve my problem:
My static file do not live in the Views folder and it also does not address opening the page in a new tab.
EDIT 2 - Solution
Since this cannot be done directly from the controller I implemented the following in my View's scripts.
$('#linkAppHelpButton').off().on('click', function () {
$.ajax({
type: "GET",
url: '#Url.Action("ReturnHelpPage", "Help", null)',
data: { identifier: "index" },
success: function (page) {
window.open(page, '_blank');
},
})
});
Since controllers are processed on the server side, it is not possible to control aspects of the browser such as "open in a new tab".
You can (as you have discovered) serve an HTML file through a controller action or just allow the web server to serve it directly. But the only options for opening the content in a new tab are to use <a target="_blank" href="some URL">new tab</a> or use JavaScript.

Which view is opened first? ASP.NET MVC

I'm wondering where can I set which of my views will be opened first when I run my application? For example I have a Login folder that contains Login.cshtml view and I would like to show that view when my application is started?
Here is my RouteConfig (RIGHT NOW REGISTER PAGE IS OPENING IN MY PROJECT AND I COULDN'T FIND ANYTHING RELATED TO REGISTER FILE HERE, SO THAT'S REASON WHY I'M CONFUSED, WHERE THIS IS SET TO OPEN REGISTER VIEW WHEN MY MVC APP IS RUNNED) file :
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 }
);
}
As you can see there is written HomeController and action method Index, so here is Home controller:
[BaseAuthorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
Again, here is nothing related to register view.. :(
How can I do it? Where to look if I want to set page/view that will be displayed when application is runned?
Probably this logic is written in BaseAuthorize I will figure it out soon, but I'm wondering what is anyway right way to do this?
Thanks guys
Cheers
Your default route, i. e. the page that will be opened when you access http://localhost, is the HomeController Index view, as per your route configuration.
Now, your controller is annotated with BaseAuthorize, which means the access to Home/Index requires authentication. If the request is not authenticated, then the it will be redirected to another page, which is probably the page you are getting.
There are two way to set your default page: you can change the route config to point to another controller/action, or you can change the default url to be whatever you want. You can set your project url via right click on your project > properties > web > project url.

ASP.NET MVC trying to redirect to another page after submit

In the View, I have the following code :-
#using(Html.BeginForm("addsurvey","survey")) {
When the submit button is pressed, the event
[HttpPost]
public ActionResult addsurvey(Survey oSurvey)
{
is called but then the page errors because it can't find addsurvey.aspx etc pages. What am i don't wrong. The page that the form is on is called survey. Why can't it just refresh the page or do i need to
response.redirect("/survey");
Your method must return an ActionResult. Usually it's a ViewResult when you use return View(), but if you want to redirect to another action, there is another return type. Just do :
return RedirectToAction("Index", "survey");
(just replace Index with the target action)
Inside the addsurvey action method you can call
View();( There must be addsurvey.cshtml in the controller folder of project's View folder )
View("actionName") ;( There must be actionName.cshtml in the controller folder of project's View folder ) or
RedirectoAction("actionName","controllerName") ( There must be actionName.cshtml in the controllerName folder of project's View folder )

How to add MVC views to an existing ASP.NET application?

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.

How can I render Razor page from Assembly

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.

Resources