ASP.NET MVC changed view name - c#

I changed the name of view files (Index.cshtml -> Performance.cshtml), and when I execute the project, the application can't recognise the new view name. I changed the name of an action in controller accordingly (ActionResult Index() -> ActionResult Performance()). However, it keeps saying HTTP 404 error.

When you change your view name mvc application can't find a proper view for it's controller action method.
If it is your default page view( load on application start) than you also need to make changes in your Route_config file.
See the image below Change controller = " Name_of_controller" & action="name_of_action" in your case action name will be Performance.
Always Remember in mvc you can run any method using browser url
for example : controller is home & method is Performance than url will be localhost:port/home/Performance

Change the default route defined in App_Start/RouteConfig.cs file to set Performance as the default action.
Or, you can run the project with the following URL:http://localhost:port/home/Performance

Related

why am i getting this error in asp.net mvc C# [duplicate]

I am having a problem where I try to open my ASP.NET MVC application but I get the ASP.NET error page which says this:
Server Error in '/' Application.
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.
Requested URL: /EventScheduler/account.aspx/login
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053**
I am using the URL trick from this blog post and that is why I have the .aspx in the URL:
http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/
It works on my other sandbox server (not a dev machine), and now I just deployed it to my production site as a new virtual directory, but for some reason it seems like it's actually looking for a .aspx file.
Any ideas? I think I must be forgetting a step.
I got the same error when building. The default is to use URLRoute settings for navigating. If you select the "Set as Startup Page" property by right clicking any cshtml page, that throws this error because there are always a routing to the current page under the Global.asax file.
Look at Project Properties for Startup Path and delete it.
I found the solution for this problem, you don't have to delete the global.asax, as it contains some valuable info for your proyect to run smoothly, instead have a look at your controller's name, in my case, my controller was named something as MyController.cs and in the global.asax it's trying to reference a Home Controller.
Look for this lines in the global asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
in my case i had to get like this to work
new { controller = "My", action = "Index", id = UrlParameter.Optional }
Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:
Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!
You should carefully review your Route Values.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
In this case, ensure you have your Controller 'Home' as the application will fail to load if there is no HomeController with Index Action. In My case I had HomesController and I missed the 's' infront of the Home. I Fixed the Name mismatch and this resolved the issue on both my local environment and on my server.
If you're running IIS 6 and above, make sure the application pool your MVC app. is using is set to Integrated Managed Pipeline Mode. I had mine set to Classic by mistake and the same error occurred.
The page is not found cause the associated controller doesn't exit. Just create the specific Controller. If you try to show the home page, and use Visual Studio 2015, follow this steps:
Right click on Controller folder, and then select Add > Controller;
Select MVC 5 Controller - Empty;
Click in Add;
Put HomeController for the controller name;
Build the project and after Run your project again
I hope this help
Two Things Needs To Be Ensure:
1) Route should be proper in Global.ascx file
2) Don't forget to add reference of Controller Project in your Web Project (view is in separate project from controller)
The second one is my case.
Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.
I got the same error while building a MVC application.
In my case it happened because I forgot to add the string "Controller" in my controller name.
Error With
public class ProductType : BaseController
{
public ProductType()
{
}
}
Resolved
public class ProductTypeController : BaseController
{
public ProductTypeController ()
{
}
}
In your Project open Global.asax.cs then right click on Method RouteConfig.RegisterRoutes(RouteTable.Routes); then click Go To Definition
then at defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional}
then change then Names of "Home" to your own controller Name and Index to your own View Name if you have changed the Names other then "HomeController" and "Index"
Hope your Problem will be Solved.
Step 1 : Check to see if you have received the following update? http://support.microsoft.com/kb/894670 If you have you might want to follow this procedure and see if it works for you. It worked partially for me.
The item where it mentions the additional "/" to be removed is not entirely true but it did give me some insight to change my project properties just a bit.
step 2 : Right click on your properties for your Web Project in your Solun.
Select WEB > Choose Current Page instead of Specific Page.
step 3 : Go into your project where you keep your *.aspx's select a start page. (Should be the same as the current page or choose another one of your choice :) )
Hit Debug Run.
Suppose source code copy from other places.
Sometime, if you use Virtual Directory in your application url like:
http://localhost:50385/myapp/#/
No route will pick up the request.
solution:
Explicitly click the button 'create a virtual directory' in your project file.
Go to any page you want to see it in browser right click--> view in browser.
this way working with me.
Upon hours of debugging, it was just an c# error in my html view.
Check your view and track down any error
Don't comment c# code using html style ie
Open your Controller.cs file and near your public ActionResult Index(), in place of Index write the name of your page you want to run in the browser. For me it was public ActionResult Login().
Remember to use PUBLIC for ActionResult:
public ActionResult Details(int id)
{
return View();
}
instead of
ActionResult Details(int id)
{
return View();
}
you must check if you implemented the page in the controller
for example:
public ActionResult Register()
{
return View();
}
I had a similar problem. But I was working with Episerver locally with ssl enabled. When I wasn't getting a
Server Error in '/' Application.
I was getting a Insecure connection error.
In the end, for me, this post on PluralSight together with configuring the website urls, accordingly with the ssl link set up on the project's config, on Admin's Manage Website's screen solved the problem.
In my case, I needed to replace this:
#Html.ActionLink("Return license", "Licenses_Revoke", "Licenses", new { id = userLicense.Id }, null)
With this:
Return license
<script type="text/javascript">
function returnLicense(e) {
e.preventDefault();
$.post('#Url.Action("Licenses_Revoke", "Licenses", new { id = Model.Customer.AspNetUser.UserLicenses.First().Id })', getAntiForgery())
.done(function (res) {
window.location.reload();
});
}
</script>
Even if I don't understand why. Suggestions are welcome!
For me its solved follow the following steps :
One reason for this occur is if you don't have a start page or wrong start page set under your web project's properties. So do this:
1- Right click on your MVC project
2- Choose "Properties"
3- Select the "Web" tab
4- Select "Specific Page"
Assuming you have a controller called HomeController and an action method called Index, enter "home/index" in to the text box corresponding to the "Specific Page" radio button.
Now, if you launch your web application, it will take you to the view rendered by the HomeController's Index action method.
It needs you to add a Web Form, just go to add on properties -> new item -> Web Form. Then wen you run it, it will work. Simple
I had the same problem caused by my script below. The problem was caused by url variable. When I added http://|web server name|/|application name| in front of /Reports/ReportPage.aspx ... it started to work.
<script>
$(document).ready(function () {
DisplayReport();
});
function DisplayReport() {
var url = '/Reports/ReportPage.aspx?ReportName=AssignmentReport';
if (url === '')
return;
var myFrame = document.getElementById('frmReportViewer');
if (myFrame !== null) {
if (myFrame.contentWindow !== null && myFrame.contentWindow.location !== null) {
myFrame.contentWindow.location = url;
}
else {
myFrame.setAttribute('src', url);
}
}
}
</script>

How to change name of .cshtml file on asp.net mvc?

I created a Asp.net mvc project on visual studios, In the many folder I get I have a folder called Home that has three .csthml files: about.cshtml, contact.cshtml, and index.cshtml.
I would like to change about.cshtml to blah.cshtml and contact.chstml to lala.cshtml.
I've tried to do it from properties but the name is not changed across other files in the project.
Should I use those files in my project or create another controller?
click on the file, push F2 and then rename (type in the new name) or right click the file and select rename. Make sure that you are not running the application (which may be the issue).
If you do change the name, the action in the controllers should also probably be updated.
Also, you can rename only view and then set [ViewName()] attribute for the action.
For instance, you renamed about.cshtml to blah.cshtml:
[ViewName("~/Views/Home/blah.cshtml")]
public ViewResult About()
{
...
return View();
}
However, better keep names the same

Routing with Dashes in ASP.NET MVC

I am working on an app with ASP.NET MVC 5. I want my app to have a route that looks like the following:
http://www.myserver.com/my-category
Please notice how the route has a dash (-) in it. I currently have a controller named MyCategoryController. It is defined like this:
namespace MyApp.Controllers
{
[RoutePrefix("my-category")]
public class MyCategoryController : Controller
{
// GET: List
public ActionResult Index()
{
return View();
}
}
}
The view is located in /Views/My-Category/Index.cshtml. When I try to access http://www.myserver.com/my-category in the browser, I get an error that says:
The resource cannot be found.
I set a breakpoint and I noticed that the breakpoint is not hit. I then enter http://www.myserver.com/mycategory into the browser, and I get an error that says:
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/mycategory/Index.cshtml
~/Views/mycategory/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
How do I setup my ASP.NET MVC so that
a) I can visit http://www.myserver.com/my-category and
b) Load the view from /Views/my-category/Index.cshtml
You need to name the views folder like the controller not like the route.
So /Views/MyCategory/Index.cshtml and not /Views/My-Category/Index.cshtml.
If you, for a reason I can't imagine why, want it to be /Views/My-Category/Index.cshtml you need to "fully quallify the view":
return View("~/Views/My-Category/Index.cshtml");
About the route with the dash: I am not using attribute based routing so I can only guess:
Did you add the routes.MapMvcAttributeRoutes(); in your RegisterRoutes method?
Because http://www.myserver.com/mycategory is routed by the default "{controller}/{action}/{id}" route...

Why doesn't "views" work correctly as an MVC route prefix?

I'm trying to use attribute routing to create a generic action for client-side (specifically AngularJS) templates, so that I don't need a bunch of individual actions for every view.
Here's what I originally tried:
[RoutePrefix("views")]
public class ViewsController : Controller
{
[Route("{area}/{viewName=get}")]
public ActionResult Get(string area, string viewName)
{
return View("~/app/views/" + area + "/" + viewName + ".cshtml");
}
}
Let's say I have a "get.cshtml" view in the folder app/views/home.
What I've noticed is the following:
If I try to hit /views/home/get, it works correctly.
If I try to hit /views/home, I get a 404 and the method never gets executed.
If I change the controller name to FooController (i.e. thought it might be a conflict between convention vs. attribute routing) and try to hit /views/home, I still get a 404.
If I remove all of the "standard" routes and only use attribute-based routing, I still get a 404. So it definitely doesn't seem to be a conflict.
If I change it to [RoutePrefix("view")] and try to hit /view/home, it does work correctly.
Why does this happen? Is it a bug in the attribute routing? Is it some kind of special keyword or reserved word in MVC routing? Does it have something to do with the default MVC "views" folder, which still exists with its web.config and so on?

how does asp.net mvc relate a view to a controller action?

I have opened a sample ASP.NET MVC project.
In HomeController I have created a method (action) named MethodA
public ActionResult MethodA()
{
return View();
}
I have right clicked on MethodA and created a new view called MethodA1
Re-did it and created a new view called MethodA2.
How is this magical relationship done? I looked for the config to tell the compiler that views MethodAX are related to action MethodA, but found none.
What view will the controller return when MethodA is called?
The convention is that if you don't specify a view name, the corresponding view will be the name of the action. So:
public ActionResult MethodA()
{
return View();
}
will render ~/Views/ControllerName/MethodA.cshtml.
But you could also specify a view name:
public ActionResult MethodA()
{
return View("FooBar");
}
and now the ~/Views/ControllerName/FooBar.cshtml view will be rendered.
Or you could even specify a fully qualified view name which is not inside the views folder of the current controller:
public ActionResult MethodA()
{
return View("~/Views/Foo/Baz.cshtml");
}
Now obviously all this assumes Razor as view engine. If you are using WebForms, replace .cshtml with .aspx or .ascx (if you are working with partials).
For example if there is no view it will even tell you where and in what order is looking for views:
Remember: ASP.NET MVC is all about convention over configuration.
The MVC framework use convention over configuration. The framework calls the ExecuteResult on the ViewResult object (created by the return View();). The framework by convention then looks in a number of locations to find a view
If you are using areas the framework will look in the following locations for a view.
/Areas//Views/ControllerName/ViewName.aspx
/Areas//Views/ControllerName/ViewName.ascx
/Areas//Views/Shared/ViewName.aspx
/Areas//Views/Shared/ViewName.ascx
/Areas//Views/ControllerName/ViewName.cshtml
/Areas//Views/ControllerName/ViewName.vbhtml
/Areas//Views/Shared/ViewName.cshtml
/Areas//Views/Shared/ViewName.vbhtml
Without areas (or if you are using areas and no view has been found) the framework will look at the following locations
/Views/ControllerName/ViewName.aspx
/Views/ControllerName/ViewName.ascx
/Views/Shared/ViewName.aspx
/Views/Shared/ViewName.ascx
/Views/ControllerName/ViewName.cshtml
/Views/ControllerName/ViewName.vbhtml
/Views/Shared/ViewName.cshtml
/Views/Shared/ViewName.vbhtml
As soon as the Framework tests a location and finds a file, then the search stops,
and the view that has been found is used to render the response to the client.
There are a number of overriden versions of the View method. The most common one is to render a specific view, outside of the framework convention, by calling it by name. For example
return View("~/Views/AnotherIndex.cshtml");
As an interesting footnote, the framework looks for legacy ASP, C# and VB Razor views (aspx, ascx, cshtml and vbhtml) even though you have a specific view engine.
In MVC controller action is not bound to view.
It uses delegate mechanism to pickup the view.
Model Binding(Mapping)
I was looking for the same and I just made a couple of tests and figured out.
It doesn't save anywhere.
To understand how it works; just do these steps:
In your controller, right click, Add View
Then enter a different View Name
and Ctrl F5
you will get Server error in application.
For example if you right click , Add View in following Index action method and type "Index2" in View name, you will get the error.
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
}
So basically there is a 1-1 matching between action name and View name. And you cannot add view for the same method so there is no need to save in a config file.
Now change the view file name in Visual Studio from Index2.cshtml to Index.cshtml then Ctrl+F5. You should see it is working.

Categories