directly accessing area through url - asp.net-mvc

I'm developing an application using MVC 5. I have added a new area which contains a view called Register and gradually adding content to it. For debugging purposes, I'm trying to access that area directly through url after logging in to application. I'm using the url: http://localhost:port/Area/Account/Manage/Register
But I'm getting error. How will be the url, If need to view Register page directly. Please find the directory structure below:

You cannot access the view file directly. You should access it via an action method.
Create an action method called Register in your ManageController (if not exists) and return the view
public ActionResult Register()
{
return View();
}
now you can access this by navigating to yoursitename/account/manage/register assuming you haven't altered the default route registration for the area.

Related

Redirect from one MVC to another MVC application with querystring

Using .net core 2.0 MVC, C#
I have an application in MVC that has a menu on the UI. One of the menu item contains the redirect to another application. So when user clicks on that item I make an redirect to another application within the same IIS.
So I wanted to know:
- What is the best approach to make an redirect to another application withing the same IIS. Basically to another controller and action in the target application.
- How can I pass some querystring params along the redirect. I want to pass a string value.
- On the target application whats the best place to grab the query string values?
Would appreciate inputs.
Thanks
Hosted on the same server or not, applications are separate entities. In other words, if you need to link to another website (whether it be one you control or not), you'll need to include the full absolute URL:
Click me!
There's no way to generate this as you could for a URL internal to your web app. You also simply construct the query string you want manually, since again, there's no way to generate this for a separate web app.
On the other side, this is just basic modelbinding. Generally speaking, any query string value can be bound directly to an action param of the same name. For example, with the address above, you'd just need an action like:
public IActionResult Index(string key)
Inside App1 View (cshtml):
Link
Inside app2 home controller
public ActionResult Test(string name)
{
//do whatever you want with name.
return View();
}

How to view MVC .cshtml file as html?

How exactly does one render a .cshtml file?
I'm new to ASP.NET. I've created an MVC project using Visual Studio's template. Apparently all the templates have .cshtml for the Default / Index files. But my server gives me this error when I try to view it:
Server Error in '/' Application. This type of page is not served.
Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.cshtml' may be incorrect. Please review the URL below and make sure that it is spelled correctly.
Requested URL: /mobile/WebApplication1/Index.cshtml
So, how exactly do I view the Index file? Do I need to pass it through something to convert to .html or render it somehow?
Files with extension .cshtml in the context of ASP.NET MVC are views. They cannot be viewed (served by the web server) just by themselves. You need a controller action that will render the view.
NOTE: you could employ some "tricks" to modify IIS settings and your app to enable serving .cshtml files to browser requests, but this would not be normal behaviour.
Assuming your view is located at ~/Views/Index.cshtml here is a (trivial) example of a simple controller action:
public class ExampleController : Controller
{
public ActionResult Index()
{
return View();
}
}
This controller should be placed at: ~/Controllers/ExampleController.cs
You will access the rendered page at: localhost/example/index
More about ASP.NET MVC here: http://www.asp.net/mvc/overview/getting-started/introduction/getting-started
You can not access an MVC view directly by its name. Ever...!
What you can do is call a Controller action, and that is done through an URL such as /WebApplication1/Index.
The above URL means two things:
there has to be a class called WebApplication1Controller.cs,
and that class must have a method public ActionResult Index().
The method Index will then determine which View (if any) is going to be displayed, and also what data will be sent to that view to use.
If the method Index executes return View(); then there is an implicit rule that the view with the same name (in this case Index.cshtml) is going to be shown.
Or if for some reason Index executes return View("Wow"); instead, then the view called Wow.cshtml will be displayed.

How do I call a method on one controller from another in .NET 4 MVC

In an asp.net MVC application, I need to produce some documens, HTML and PDF, which are not sent to the user's browser, but either sent by mail or entered in our document journalizing system. I produce these documents using Razor.
When a document is used only once, I just add a method to the relevant controller, and the view to that controller's view folder. This works. But I have a document that must be produced at two places in the application, implemented in separate controllers. I have made a new controller for this document with its own view folder.
My question is now: how do I call a method on this controller? Searching the web gives many answers, but all redirect the user to this document, which is not what I need.
You can just call it like you would any other method e.g.
public ActionResult DoSomething()
{
// Some code
var otherController = new OtherController(); // The other controller where the method is
otherController.CreatePdf(); // Call the method
// Continue with what ever else you need to do
return View(); // This will then return the `DoSomething` View
}
But personally it doesn't seem like this logic belongs in a controller. You should possibly think about refactoring this logic out of a controller and into a more logical place. Possibly create your own document generation class and use that.
If I'm getting you right.You could create a base controller and add the method there. You can inherit the Base controller in any controller where you want to call the method. here's a link that might help show you the use of Base controllers. How to wire common code from a base controller in ASP.NET MVC.

The view 'Index' or its master was not found.

The view 'Index' or its master was not found. The following locations were searched:
~/Views/ControllerName/Index.aspx
~/Views/ControllerName/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
I got this error when using ASP.Net mvc area. The area controller action are invoked, but it seems to look for the view in the 'base' project views instead of in the area views folder.
What you need to do is set a token to your area name:
for instance:
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
).DataTokens.Add("area", "YOURAREANAME");
This error was raised because your Controller method name is not same as the View's name.
If you right click on your controller method and select Go To View (Ctrl+M,Ctrl+G), it will either open a View (success) or complain that it couldn't find one (what you're seeing).
Corresponding Controllers and View folders name have the same names.
Corresponding Controller methods & Views pages should same have the same names.
If your method name is different than view name, return view("viewName") in the method.
Global.asax file contain the URL Route.
Default URL route like this.
"{controller}/{action}/{id}"
So,Try this.
1. Right click your controller method as below.
Example: let say we call Index() method.Right click on it.
2. Click Add View.. and give appropriate name.In this example name should be Index.
Then it will add correct View by creating with relevant folder structure.
Check the generated code at MyAreaAreaRegistration.cs and make sure that the controller parameter is set to your default controller, otherwise the controller will be called bot for some reason ASP.NET MVC won't search for the views at the area folder
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
);
}
Where this error only occurs when deployed to a web server then the issue could be because the views are not being deployed correctly.
An example of how this can happen is if the build action for the views is set to None rather than Content.
A way to check that the views are deployed correctly is to navigate to the physical path for the site on the web server and confirm that the views are present.
The problem was that I used MvcRoute.MappUrl from MvcContrib to route the context.Routes.
It seems that MvcContrib routing mapper was uncomfortable with area routing.
You most likely did not create your own view engine.
The default view engine looks for the views in ~/Views/[Controller]/ and ~/Views/Shared/.
You need to create your own view engine to make sure the views are searched in area views folder.
Take a look this post by Phil Haack.
I had this problem today with a simple out of the box VS 2013 MVC 5 project deployed manually to my local instance of IIS on Windows 8. It turned out that the App Pool being used did not have the proper access to the application (folders, etc.). After resetting my App Pool identity, it worked fine.
right click in index() method from your controller
then click on goto view
if this action open index.cshtml?
Your problem is the IIS pool is not have permission to access the physical path of the view.
you can test it by giving permission. for example :- go to c:\inetpub\wwwroot\yourweb then right click on yourweb folder -> property ->security and add group name everyone and allow full control to your site . hope this fix your problem.
It´s still a problem on the Final release.. .when you create the Area from context menu/Add/Area, visual studio dont put the Controller inside de last argument of the MapRoute method. You need to take care of it, and in my case, I have to put it manually every time I create a new Area.
You can get this error even with all the correct MapRoutes in your area registration. Try adding this line to your controller action:
If Not ControllerContext.RouteData.DataTokens.ContainsKey("area") Then
ControllerContext.RouteData.DataTokens.Add("area", "MyAreaName")
End If
If You can get this error even with all the correct MapRoutes in your area registration and all other basic configurations are fine.
This is the situation:
I have used below mentioned code from Jquery file to post back data and then load a view from controller action method.
$.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'});
Above jQuery code I didn't mentioned success callback function.
What was happened there is after finishing a post back scenario on action method, without routing to my expected view it came back to Jquery side and gave view not found error as above.
Then I gave a solution like below and its working without any problem.
$.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'},
function (data) {
var url = Sys.Url.route('PetDetail', { action: "ReturnRetailOnlySalesItems", controller: "Customers",petKey: '<%: Model.PetKey %>'});
window.location = url;});
Note: I sent my request inside the success callback function to my expected views action method.Then view engine found a relevant area's view file and load correctly.
I have had this problem too; I noticed that I missed to include the view page inside the folder that's name is same with the controller.
Controller: adminController
View->Admin->view1.cshtml
(It was View->view1.cshtml)(there was no folder: Admin)
This error can also surface if your MSI installer failed to actually deploy the file.
In my case this happened because I converted the .aspx files to .cshtml files and visual studio thought these were brand new files and set the build action to none instead of content.
I got the same problem in here, and guess what.... looking at the csproj's xml' structure, I noticed the Content node (inside ItemGroup node) was as "none"... not sure why but that was the reason I was getting the same error, just edited that to "Content" as the others, and it's working.
Hope that helps
Add the following code in the Application_Start() method inside your project:
ViewEngines.Engines.Add(new RazorViewEngine());
I added viewlocationformat to RazorViewEngine and worked for me.
ViewLocationFormats = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Areas/Admin/Views/{1}/{0}.cshtml",
"~/Areas/Admin/Views/Shared/{0}.cshtml"
};

Can MVC routing be used to create a dynamic content management system with dynamic pages stored in db rather than in view pages

Are there any good examples of mvc routing wherein every 404 page not found request is routed to a standard view in MVC which basically pulls the content from the database.
Just add this route to the bottom of your RouteTable:
routes.MapRoute("DynamicPages", "{*page}", new { Controller = "DynamicPages", Action = "Show", Page = String.Empty });
And create a controller for displaying dynamic pages from db:
public class DynamicPagesController : Controller
{
public ActionResult Show(string page)
{
var pageContent = DB.GetContentForPage(page);
return Content(pageContent);
}
}
Here's one way to do this: In your global.asax file in Application_Start, you need to set the default controller factory. Override it with an instance of your own factory.
void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
}
MyControllerFactory should inherit from DefaultControllerFactory and when selecting the controller to use, look in your database for the appropriate page you want to display. If the page exists, select the appropriate controller and override the action in the requestContext.RouteData collection to point at the appropriate action for displaying dynamic pages.
If the requested page doesn't exist, pass back a call to the base method and let it do what it would normally do.
There are other ways you could do it, but this one should work and allows you to intercept the request before you hit the 404 page.
modify the web.config file, you may Reference to this page and look at the setting custom error pages in web.config section.

Resources