MVC 4 routing to a controller - asp.net-mvc

I am new to MVC and I am trying to mess around by creating a practice site which will be a gallery site for viewing and uploading images. The problem I encountered is that I cannot get the routing to work correctly.
Here is a link to my routing code and solution tree:
https://imgur.com/a/Oc1Tt?
Did I set the views and controller up incorrectly?
The error I get is: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
Thanks for any input

Routing works by converting an incoming request to route values or by using route values to generate a URL. The route values are either set as parameters in the URL itself, as default values, or both (in which the defaults make the URL parameters optional).
You have not set any route values in your route. Since you don't have route parameters in the URL, you need to set defaults (controller and action are required by MVC).
routes.MapRoute(
name: "Gallery",
url: "Gallery/Index",
defaults: new { controller = "Gallery", action = "Index" }
);
That said, your Default route already covers this URL. You only need to add custom routes if you desire behavior that the Default route doesn't cover.
Also, if you change the view names so they don't match the name of the action method, you have to specify the name explicitly from the action method.
public ActionResult Index()
{
return View("~/Views/Gallery/GalleryView.cshtml");
}
By default MVC uses conventions. It is much simpler just to name the view Index.cshtml instead of GalleryView.cshtml so you can just return View from the action method.
public ActionResult Index()
{
return View();
}

Related

.net Core - Default controller is not loading when Route attribute is used

A new .net core web application project comes with the following route configuration:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
If you replace this with app.UseMvc() and add appropriate Route attributes for both HomeController and its actions (Index, About, Contact, Error), it would still work. Since we're not specifying a default route, the default view (Home/Index) will not be rendered if you hit http://localhost:25137/. Hope that understanding is correct!
Now, since I need the default view to be shown when the http://localhost:25137/ is hit, I changed the routing code to app.UseMvcWithDefaultRoute(); which by definition will do the equivalent to the initial snippet. Even then, it was not rendering the default view; but worked when used the complete URL(http://localhost:25137/home/index). That means the routing still works but not the default one!
Then I went back to the controller and removed all the Route attribute from the HomeController and its actions. Then the default routing worked with out any issues.
Is that the expected behavior?
What could be the reason behind this behavior?
From the asp docs:
Actions are either conventionally routed or attribute routed. Placing
a route on the controller or the action makes it attribute routed.
Actions that define attribute routes cannot be reached through the
conventional routes and vice-versa. Any route attribute on the
controller makes all actions in the controller attribute routed.
So basically if you use attributes then the routes defined in UseMvc or UseMvcWithDefaultRoute will be ignored. Only the attribute would be used in that case.
You could still use multiple route attributes if you wanted to achieve a similar effect than the default route with optional segments. Again from the same article in the asp docs:
public class MyDemoController : Controller
{
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult MyIndex()
{
return View("Index");
}
[Route("Home/About")]
public IActionResult MyAbout()
{
return View("About");
}
[Route("Home/Contact")]
public IActionResult MyContact()
{
return View("Contact");
}
}

Routing values to the MVC Player function?

In a Composite C1 application, I am trying to pass values from the URL to the MVC Player function, but I have trouble because the values are part of the path and not in the query string.
The URL looks like this:
/AuctionDetailsGallery/3624734/Test-Versteigerung-2
AuctionDetailsGallery is a Composite C1 Page which includes the MvcPlayer function.
3624734 is the (dynamic) ID, "Test-Versteigerung-2" is a userfriendly name
The MvcPlayer is then supposed to call
/AuctionViewer/FilterGalleryPositions
("AuctionViewer" is the controller and "FilterGalleryPositions" the action.)
The ID has to be passed to the action, but under a different name ("SelectedAuctions").
So essentially, if the user calls
/AuctionDetailsGallery/3624734/Test-Versteigerung-2
I want to render the MVC action
/AuctionViewer/FilterGalleryPositions?SelectedAuctions=3624734
How can I do this?
I set the MvcPlayer path to "/AuctionViewer/FilterGalleryPositions" and played around with the routes, but I always get the message
The controller for path '/3624734/Test-Versteigerung-2' was not found
or does not implement IController.
That's because the Render function checks for PathInfo and replaces the Path I set with the PathInfo if available. I guess it would be more useful if the PathInfo was appended, but I am unsure how to route my values with the current MVC Player implementation.
If I understand your question correctly I believe you are asking about routes.
With Attribute routing simply declare the route over the controller action (assuming controller name is AuctionViewerController):
[Route("AuctionDetailsGallery/{selectedAuctions}/Test-Versteigerung-2")]
public ActionResult FilterGalleryPositions(int selectedAuctions)
{
...
}
With a routetable you might define something like this:
routes.MapRoute(
name: "AuctionDetails",
url: "AuctionDetailsGallery/{selectedAuctions}/Test-Versteigerung-2",
defaults: new { controller = "AuctionViewer", action = "FilterGalleryPositions" }
);

ASP.NET MVC Dynamic Action with Hyphens

I am working on an ASP.NET MVC project. I need to be able to map a route such as this:
http://www.mysite.com/Products/Tennis-Shoes
Where the "Action" part of the URL (Tennis-Shoes") could be one of a list of possibilities. I do not want to have to create a separate Action method in my controller for each. I want to map them all to one Action method and I will handle the View that is displayed from there.
I have this working fine by adding a route mapping. However, there are some "Actions" that will need to have a hyphen in them. ASP.NET MVC routing is trying to parse that hyphen before I can send it to my action. I have tried to create my own custom Route Handler, but it's never even called. Once I had a hyphen, all routes are ignored, even my custom one.
Any suggestions? Details about the hyphen situation? Thanks you.
Looking at the URL and reading your description, Tennis-Shoes in your example doesn't sound like it should be an action, but a Route parameter. Let's say we have the following controller
public class ProductsController : Controller
{
public ActionResult Details(string product)
{
// do something interesting based on product...
return View(product);
}
}
The Details action is going to handle any URLs along the lines of
http://www.mysite.com/Products/{product}
using the following route
routes.MapRoute(
null,
"Products/{product}",
new
{
controller = "Products",
action = "Details"
});
You might decide to use a different View based on the product string, but this is just a basic example.

404 asp.net mvc - beginner question in routing

This is a beginner level question for asp.net MVC
I have the following code in global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = (string)null } // Parameter defaults
);
}
in Homecontroller.cs i have updated the Index method as follows
public ActionResult Index(string id)
{
ViewData["Message"] = "Welcome to ASP.NET MVC1!"+ id;
return View();
}
My understanding is, if I give the url http://localhost/mvc1/default/1 it should work
instead it is throwing up 404 error
any help what is the reason behind this
I'm assuming your application is called "mvc1" and that's the root of your project. If that's the case:
So "default" is the name if your route, not the name of the action. Basically what the routing engine does is look for a controller and action that matches requests coming in. Given the route you have setup, it would break down like this:
http://localhost/MVCApplication1/default/1
(cont) (action)
If certain parts of the route are omitted, it will attempt to fill in the missing values with the defaults you have specified. As you can see, there is no controller named DefaultController in your project, and thus it uses the default you've specified which is Home. It then tries to find an action method called default and fails again, so it uses the default value in your route, which is Index. Finally, you have 2 segments left in your URL, and no route matches that pattern (2 segments after the action), so it can't find the right place to go.
What you need to do is remove one of your segments, and this should work. Routing can be a little tricky, so I would recommend reading up on it.
The URL you're requesting is asking for a controller called "mvc1" and an action called "default" which will receive an id of "1". Since you don't have a controller named "mvc1" (I assume?), you're getting the 404 error.
The defaults for controller and action are only used if controller and action aren't provided. Since you provided controller and action, MVC is looking for them specifically.

How to use QueryString

How can I have different URL ids like www.somewebsite.com/index?theidentifier=34 only in ASP.NET MVC not Webforms.
Well, for what purpose? Just to access the value? All querystring values can be routed to params in the action method like:
public ActionResult index(int? theidentifier)
{
//process value
}
Or, you can use the QueryString collection as mentioned above, I think it's via this.RequestContext.HttpContext.Request.QueryString.
If you want to handle your routing in ASP.NET MVC, then you can open Global.asax and add calling of routes.MapRoute in RegisterRoutes method.
The default routing configuration is {controller}/{action}/{id} => ex:
http://localhost/Home/Index/3 , controller = HomeController, Action=About, id=3.
You may add something like :
routes.MapRoute(
"NewRoute", // Route name
"Index/{id}", // URL with parameters
new { controller = "Home", action = "Index",id=1 } // Parameter defaults
);
so http://localhost/Index/3 will be accepted
Remember to add these code above the default route configuration, because ASP.NET will search for the first matching route

Resources