I'm new on asp.net mvc. I created a basic controller and I tried to open it using url. But rendering is not finished and my controller didn't display in several minutes. I did not change anything from default asp.net 5 mvc project also my controller's index method return only hello world string. I don't is there any problem on iis or VS. Any idea about that problem?
Thanks for help.
In MVC only public methods that return an ActionResult are accessible as web pages.
So you MUST use something like this:
public class HelloWorldController : Controller
{
// GET: HelloWorld/Index
public ActionResult Index()
{
return Content("This is <b>Index</b> action...");
}
// etc
}
Content(...) is a special method the wraps text into an ActionResult.
Note: only use Content(...) if you specifically do NOT want to use a View such as Index.cshtml - which is what you normally WOULD do, of course.
Related
I am using ASP.Net MVC 5 for web development. I have added many Views and they are working. But if I try to add a new View, it cannot be navigated by browser i.e. 404 error occurred. But the rest of the Views are working correctly.
I tried to add new Views in distinct controllers but they have the same problem.
Please help me to solve this issue.
Created a new view in MVC 5, opening the new view results in HTTP 404
You should be accessing the view through an action method. So If you
created your new view in ~/Views/Home/AboutMe.cshtml, You should add
an action method like this in your HomeController.
public class HomeController : Controller
{
public ActionResult AboutMe()
{
return View();
}
}
Now you can access this like
http://yourServerName/yourAppName/Home/AboutMe
If you want to have your action method in a different controller, You
can specify the full view path. Ex : IF you want to add the action
method to your Account controller,
public class AccountController : Controller
{
public ActionResult AboutMe()
{
return View("~/Views/Home/aboutme.cshtml");
}
}
This question already has answers here:
How to serve html file from another directory as ActionResult
(6 answers)
Closed 5 years ago.
We have a .NET 4.0, MVC 2 project, where the HomeController looks like this:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View("~/client/index.html");
}
}
All is fine.
But, when we start linking to .NET 4.5 and MVC 4, the runtime can't seem to find this index.html! We get this error:
The view '~/client/index.html' or its master was not found or no view
engine supports the searched locations. The following locations were
searched: ~/client/index.html
How could this be! What might we be missing here.
I've never seen MVC using straight html pages. This is a more typical setup:
Controller
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index");
}
}
The view would be /views/Home/Index.cshtml. By default MVC wants views to be in the views folder in a folder corresponding to the controller name.
If you want to have the layout broken into a separate file it would typically be in /views/Shared/.
If your HTML page is self-contained you should be able to move it and rename it to index.cshtml and add the following somewhere on the page.
#{
Layout = null;
}
Take care when locating your html page. Placing it inside a view folder where, by the MVC rules, a controller would be expected to do the handling, causes errors in my testing. Here's one way to make it work, though this isn't really coding to MVC pattern:
You can then reference the page:
Notice I've stepped outside the controller/view structure (not recommended for MVC)
To make it fail, which I'm assuming is similar to what is happening for you:
(notice the html is placed in a view where we'd expect a matching controller method to serve it to a caller)...
But...
So if you insist on going this approach perhaps you can set up a content folder outside your MVC controller/view structure and place your html there. But, again, not to beat the subject to death, you could easily convert this to cshtml and serve it up via a simple method in a controller. Just my two cents' worth..
I have recently started working on MVC application. However my first plan was to create two separate projects in the same solution. One asp.net MVC web application and second is asp.net WebAPI. So that my Web Application will talk to Web API which in return will send JSON response to application which will be converted to View Model for View.
Workflow Diagram :
As i studied more i got to know that API controller and controller both merged into a single controller class in MVC 5. so here is my question how can i achieve the above workflow in MVC 5.
MVC 5 Workflow Diagram
So here comes the problem for me in MVC 5 or i am unable to understand it completely E.g :
UserModel
public class UserModel
{
Public int UserId {get;set;}
Public string Username {get;set;}
}
UserController
[HttpGet()]
public IActionResult GetUser(int id)
{
// do some work
return View(userObject);
}
View
#model UserModel
<h1>#Model.Username</h1>
but when i call the above method from mobile it will give me the rendered html which is not useful for me so do i need to create another method in the same controller in which will return data in JSON.
[HttpGet()]
public IActionResult ApiGetUser(int id)
{
// do some work
return JSONResponse.. ;
}
Modifying method :
[HttpGet()]
public IActionResult GetUser(int id)
{
// calling api get user method
ApiGetUser(int id); // return json
// do some work to convert json into ModelObject
return View(userObject);
}
And if any one mobile app needs data it can call m APIGetUser Method but in this scenario for me its tedious and no of extra methods will be added in the same class. So my basic question is my understanding towards the flow is wrong or am i missing somethings because if below mentioned workflow is right than i would prefer the first one as its separate WebAPI project and easy to maintain ?
In my opinion both diagram are architecturally correct.
But you should consider SRP and separation of concern this: if MVC controller + WebApi controller are both an entry point to your application, running the same code and returning it in 2 different way, they are actually doing 2 different things isn'it? One serve the view and the other one the json.
Plus if you have to render a view there are naturally some behaviuour that isn't common with your web api (cache or rendering partial view for example).
If you think the same, you should leave aside that in MVC 5 both MVC+WebApi controller are under the same class and split it for the reason above.
Hope it helps!
I have a ASP.NET MVC 4 Blog which is 90% done but i need one thing - i have a webpage lets say index/secretPage but i want to be able to navigate to this webPage only after i am redirected from another - lets say index/redirect . If the adress is hardcoded it should not navigate, if the visitor is coming from a different link like blog/post/24 it should not be able to navigate too.
I hope my question was clear, than you for all help.
You could also mask the secret page with an action that shows another page if direct called.
In this example there are 2 actions. 'Secret' for returning a bogus view and the 'Check' for the real call. In this action the bool variable 'allowSecret' ist checked an then the user sees the view 'secret.cshtml' if allowed or 'index.cshtml' if not.
Here's an example code for a simple controller with that functionality:
using System.Web.Mvc;
namespace Test.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index");
}
public ActionResult Check()
{
// check if user is allowed to show secret page
if(allowSecret == true)
return View("Secret");
// Otherwise return view 'index.cshtml'
return View();
}
public ActionResult Secret()
{
// Always shows view 'index.cshtml' if url is ".../secret"
return View("Index");
}
}
}
You could also redirect to another action after the check fails instead of calling a 'fake-view':
return RedirectToAction("Index")
The difference is the url the user sees in the browser. Returning a view does not change the url, redirecting to another action changes the url to the changed route.
Of course you can place the check in another class behind the controller.
Another option is to use the 'NonAction' attribute:
[NonAction]
public ActionResult Check()
{
...
}
Hope that helps with kind regards,
DD
You can UrlReferrer to get to know who refred to this current page and throw and exception or redirect back
HttpContext.Current.Request.UrlReferrer
http://msdn.microsoft.com/en-IN/library/system.web.httprequest.urlreferrer.aspx
But for what ever reason you need this. It dosenot look like a good design to me.
Hope this helps
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.