Error 404 creating a view in mvc5 - asp.net

I am linking a SQL database to my MVC ASP.Net. I have created the model, context class, web config and controller.
However for some reason when I create a view by right clicking on the 'views' folder I get a 404 error when I debug. If I create my view by right clicking next to:
public ActionResult Index()
in the Controller class i don't get this error. Is there any reason for this?

From your question, it seems like you might be creating the View in the wrong folder.
When you add a view for a Controller/Action, you must create subdirectory in ~/Views that matches your controller's name.
For example,
public ProductController : Controller
{
public ActionResult Index()
{
return View();
}
}
You would add your Index.cshtml to Views/Product:
~/Views/Product/Index.cshtml
If you wanted to return another view called "Other.cshtml",
return View("Other");

Related

ASP.NET MVC - Cant get to my controller index page (or any other)

Ok so i got a 'web' that keeps track of books in a bookstore.
I have HomeController and BookController. I havent changed anything in RouteConfig,
nor did i touch HomeController. When i run my website (F5) it takes me to http://localhost:44328/
aka (Views > Home > ) Index.cshtml which is all right.
BUT, when i add /Book to my URL it still stays on the index.cshtml (HomeController).
I also tried with /Book/Index in url but it gives me 404 error. Even though i do have my index.cshtml in Views > Book folder.
//My BookController actions:
public ActionResult Index()
{
return View();
}
public ActionResult AddForm()
{
BookGenreViewModel vm = new BookGenreViewModel();
vm.Genres = DAL.DALGenre.GetAll();
return View(vm);
}
public ActionResult List()
{
List<Book> books = DAL.DALBook.GetAll();
return View(books);
}
Not sure if i understand this routing or whatever it is.
Anything i should know?
EDIT: when i manually go localhost:port/Book/Book it works.

HttpPost and Authorize leads to Error: Server Error in '/' Application. The resource cannot be found

In my ASP.Net (.net 4.7 + MVC5) web application I have an action Search() which leads to the an error after authorising the user. The error is as follows:
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: /Search
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.7.2106.0
The action is implemented as follows:
[Authorize]
[Route("Search")]
[HttpPost]
public ActionResult Search(SearchViewModels passedQuery)
{
//Action working code here
return View("~/Views/Home/Search.cshtml", passedQuery);
}
Form submission code as follows:
#using (Html.BeginForm("Search", "Home"))
{
<div class="form-group">
#Html.TextBoxFor(m => m.Content, new { #class = "form-control" })<br />
<button type="submit" class="btn btn-danger">SEARCH</button>
</div>
}
If I take the [HttpPost] out from the action then during debugging mode the application works perfectly even after authorising the user (No error thrown). But without using the [HttpPost] the code does nothing on the production server.
Can someone help with:
Why the error message is shown when [HttpPost] is used with
[Authroize]?
When and why to use [HttpPost]? (I have referred to few posts and
documents regarding the usage of HttpPost and HttpGet but still I
am finding it liitle hard to grasp the concept of their
appropriate usage [1], [2])
I am very new to ASP.Net and MVC development and any help is really appreciated. Thank you.
This line which returns a view makes no sense:
return View("~/Views/Home/Search.cshtml", passedQuery);
In proper usage, just use view name instead of its complete virtual path with extension and ensure that the Search method belongs to HomeController:
[Authorize]
public class HomeController : Controller
{
[HttpPost]
public ActionResult Search(SearchViewModels passedQuery)
{
return View("Search", passedQuery); // or just return View(passedQuery)
}
}
Note that AuthorizeAttribute requires authorized users who meet the specified requirements to access the method, so it's no use to set it on POST methods while submitting the form which already loaded. You need to specify AuthorizeAttribute on controller class when users requesting page they're wanted to view based from authentication roles, and set AllowAnonymousAttribute on methods which you're allow anonymous users to get through.
Hence, your Search action pair should constructed like this example:
[Authorize]
public class HomeController : Controller
{
// other stuff
[Route("Search")]
[HttpGet] // getting search page request
[AllowAnonymous] // allow anonymous users to load search page
public ActionResult Search()
{
return View();
}
[HttpPost] // posting content using inserted values on form
[AllowAnonymous] // allow anonymous users to load search page
public ActionResult Search(SearchViewModels passedQuery)
{
return View("Search", passedQuery); // or just return View(passedQuery)
}
// other stuff
}

ASP.NET Core over writing my URL

I'm having a problem where the action in my controller called GiftCards is over-writing the actual URL/View page name.
public IActionResult SomeStupidName()
{
return ("Checkout");
}
my url turns into
www.mywebsite.com/GiftCards/SomeStupidName
while I want it to be
www.mywebsite.com/GiftCards/Checkout
Some further detail would be that this is execute with an form-submit where the form has an
asp-action="SomeStupidName"
You have to understand that www.mywebsite.com/GiftCards/SomeStupidName means SomeStupidName is an action of controller GiftCards so www.mywebsite.com/GiftCards/Checkout means Checkout is an action of controller GiftCards but in your code you are returning View from GiftCards action not redirecting to other action. Lets suppose I have action name Checkout.
public IActionResult Checkout()
{
return View("Checkout");
}
It will return the view Checkout when I enter www.mywebsite.com/GiftCards/Checkout so now I can redirect to action from any other action like:
public IActionResult SomeStupidName()
{
return RedirectToAction("Checkout");
}
You can use "Attribute Routing" in Asp.Net Core. Return the proper view in your controller.Try this code !!
[Route("GiftCards/Checkout")]
public IActionResult SomeStupidName()
{
return View("Checkout");
}
Attribute routing is set of attributes to map actions directly to route templates. We can mention rewrite url inside the "()" in "[Route("")]" Attribute.
More details about attribute routing in Asp.net core : click here

Using Html.Action with a controller in a subfolder

I am building a webapge using asp.net mvc4. For organization, I would like to put some of the controllers inside a subfolder in the Controllers folder. For example:
Controllers
AccountController
BlahController
Dashboard (Folder)
ChickenController
BeefController
To use BeefController (which returns a partial view), it seems as though I should use:
#Html.Action("Index", "Dashboard/BeefDashboard")
However this gets me the following error:
The controller for path '/' was not found or does not implement IController.
How would I be able to use BeefController?
There no physical sub folder concepts in the ASP.NET MVC world. What you should do is to have an action method in Dashboard controller, which accepts a parameter and then return specific views according to that.
public class DashBoardController: Controller
{
public ActionMethod Index(string id)
{
if(id=="chicken")
{
return PartialView("Chicken");
}
else if(id=="beef")
{
return PartialView("beef");
}
return View("NotFound");
}
}
Now you can access those like
Dashboard/beef
Dashboard/chicken

asp.net mvc - Views and Controllers

How do controllers know which views to return? I thought it was by naming convention, but I have seen instances, for example in the Nerd Dinner application, where the names don't match. Where or how do I see this mapping? Thanks.
public class EmployeesController
{
public ViewResult Index()
{
return View("CustomerName");
}
}
Will search for:
Views/Employees/CustomerName.aspx
Views/Employees/CustomerName.ascx
Views/Shared/CustomerName.aspx
Views/Shared/CustomerName.ascx
That's pretty much it..
When you just return View(); without specifying a name, it searched for the view with the same name as the controlleraction. In this case, Index.aspx
There are three ways to specify a view name.
By Convention
public ActionResult MyAction {
return View()
}
That will look for a view with the name of the action method, aka "MyAction.ascx" or "MyAction.aspx"
** By Name **
public ActionResult MyAction {
return View("MyViewName")
}
This will look for a view named "MyViewName.ascx" or "MyViewName.aspx".
** By application path **
public ActionResult MyAction {
return View("~/AnyFolder/MyViewName.ascx")
}
This last one only looks in this one place, the place you specified.
It is based on the name of the Action in the Controller. Here's an example:
I have a controller named UserController.
One of my actions on that controller is named Index.
When I say return View();
It will look in the Views directory, in the User folder, for Index.aspx or Index.ascx
It will also look in the Shared folder.

Resources