Using Html.Action with a controller in a subfolder - asp.net

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

Related

Unnecessary Dotnet Core MVC "Home" and "Index" URL components?

The default routing and URL generation for Dotnet Core 2.0 MVC produces very weird URLs. I don't remember them being like this in ASP.Net MVC.
i.e. when creating creating a new site using the Dotnet Core MVC template, we see the following URLs generated:
/Home/About « I could have sworn this used to just be /About
/Manage/Index « This definitely used to be /Manage
In the first example this is the same in the current ASP.NET MVC (.NET Template) template. I don't remember seeing the "Home" in the URL. That seems weird. Why not just /About?
In the second example there's a difference between the ASP.NET MVC (.NET Template) and the Dotnet Core one. The "Index" on the end is obviously superfluous.
Anyone know what's up here? Is there a simple way to change the default route definition to clean this up?
Take a look at attribute routing which you could use to declare your routes in this fashion:
public class HomeController : Controller
{
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult Index()
{
return View();
}
[Route("Home/About")]
public IActionResult About()
{
return View();
}
[Route("Home/Contact")]
public IActionResult Contact()
{
return View();
}
}
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing#attribute-routing

asp.net mvc 4 custom urls for action method

I am creating a asp.net mvc 4 application
public class AspNetController : Controller
{
//
// GET: /AspNet/
public ActionResult Index()
{
return View();
}
public ActionResult Introduction()
{
return View();
}
}
as Shown Above There is AspNet Controller and Introduction Action Method
Default Url for Introduction Action Method is
localhost:55134/aspnet/introduction
But I Want Url Like
localhost:55134/aspnet/introduction-To-AspNet
Same for
/localhost:55134/aspnet/NetFrameWork To
/localhost:55134/aspnet/What-is-.Net-Framework
How to do that
You should be able to use the ActionName attribute to decorate your routes.
[ActionName("Introduction-To-AspNet")]
public ActionResult Introduction()
{
return View();
}
You really want to use AttributeRouting, either via a 3rd party package or natively if you can.
Technically this concept comes under Routing in ASP.NET MVC.
For this you need to do an entry for route in App_Start->RouteConfig.cs file under RegisterRoutes(RouteCollection routes)
For Example:
routes.MapRoute(
"customRouteName",
"aspnet/introduction-To-AspNet",
new { controller = "AspNet", action = "Introduction" });
here aspnet/introduction-To-AspNet will append after your base url i.e. localhost:55134/
The quick and dirty answer is to add a route to your ~/AppStart/RouteConfig.cs file and it will be taken care of:
routes.MapRoute(
name: "CustomRoute",
url: "Aspnet/Introduction-To-AspNet",
defaults: new { controller = "Home", action = "AspNet", id = UrlParameter.Optional }
);
However, I'm assuming this is for some type of blog? I would reccomend that you have an action method called view, and then use your name as a parameter for the article. That way, you don't have to go in and edit the code every time you add a new article or other content:
public class ArticlesController : Controller
{
public ActionResult ViewArticle(string? title)
{
ViewBag.Article = title;
return View();
}
}
that way, your URL would be www.yoursite.com/Articles/ViewArticle/Introduction-To-AspNet. In general, you don't want to add tons of specific routes to your route config if you can avoid it. That being said, if this is a legacy system, the route table may be the only way.
EDIT
Ok, so what you can do is pass the string into the ViewBag and use a case statement to determine which partial view to show (I think this just might be your ideal solution):
<!--cshtml view-->
#switch(ViewBag.Article)
{
case 'Introduction-To-AspNet':
#Html.Partial('pathToPartialView.cshtml')
break;
case 'Some-Other-Article'
#Html.Partial('pathToAnotherPartialView.cshtml')
break;
...
...
default:
#Html.Partial('invalidArticleName.cshtml')
break;
}
The controller will pass the article name through the ViewBagand then you can use the case statement to figure out which article to render... and of course, the real secret sauce you've been looking for: #Html.Partial('URL') - this will take your partial and render it right were you put that in the page. You can also pass objects to that just as an FYI.
In addition, make sure that you have a default action on the switch statement that will show some sort of 404 page that indicates that the name in the URL was invalid. You ALWAYS want to have this anytime you're taking user input from the URL because people monkey with URLs all the time (and more innocently, copy+paste them wrong/incompletely all the time)

Error 404 creating a view in mvc5

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");

ASP.Net WebApi: Invalid URL generated in BeginForm

I'm beginning to use WebApi and I'm having an issue with a URL being incorrectly generated
I have an ApiController like this:
public class EntriesController : ApiController
{
public HttpResponseMessage Post(Entry entry)
{
...
}
}
And I was trying to create a standard controller (i.e. not webapi) in the same project to test this api (I already tested the api with fiddler and everything is ok there).
I assumed I could use the standard HTML helpers like this:
#using (Html.BeginForm("Post", "Entries"))
However this generates the following markup:
<form action="/Entries/Post" method="post">
and I expected it to generate
<form action="/api/Entries" method="post">
What is the correct way to generate the API url from a view?
I am using the default api and controller routes.
Thanks
#using (Html.BeginForm("Post", "Entries"))
You can not put WebAPI controller and method in MVC BeginForm like above. You need to pass MVC Controller and action to the BeginForm.
You can create a WebAPI EntriesController instance in your MVC controller, then use this instance to call the WebAPI method. See below:
//MVC Controller
public class EntriesController : Controller
{
[HttpGet]
public ActionResult Entries()
{
return View();
}
[HttpPost]
public ActionResult Entries(SomeModels model)
{
if (ModelState.IsValid)
{
var api = new EntriesController(); // Create WebAPI instance Here
api.Post(model.entry);
return RedirectToAction("Index", "Home");
}
return View();
}
}
This is technically possible by doing:
#using (Html.BeginForm("Post", "api/Entries"))
Don't forget, the "Post" value in the .BeginForm() extension method doesn't mean anything to an out-of-box Web Api route setup. Only the url and HTTP action matter (and any additional values on the URL for method overloading)
You would need to use BeginRouteForm as link generation to Web API routes always depends on the route name. Also make sure to supply the route value called httproute as below.
#using (Html.BeginRouteForm("DefaultApi", new { controller="Entries", httproute="true" }))

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