user3351901
user3351901

Reputation: 107

asp.net controller not returning content(asp.net - MVC)

I am new to web apps with asp.net, I have tried to map my own url and ran into some issues. I have the following code

//controller
 public class CuisineController : Controller
{
    //
    // GET: /Cuisine/
    public ActionResult Search()
    {

        return Content("Cuisine");
    }



//Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathinfo}");

        routes.MapRoute(
            "Cuisine",
            "Cuisine/{name}",
            new { controller = "Cuisine", action = "Search", name = UrlParameter.Optional }
            );

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", aciton = "Index", id = UrlParameter.Optional}

            );


    }
}

I know this is extremely basic code, but everytime i run it with the url ~/cuisine/{name} I get an 404 error? Can someone please tell me why? Thanks!

Upvotes: 0

Views: 160

Answers (1)

DotNet NF
DotNet NF

Reputation: 833

Your problem is in this block of code

routes.MapRoute(
        "Cuisine",
        "Cuisine/{name}",
        new { controller = "Cuisine", action = "Search", name = UrlParameter.Optional }
        );

Specifically, you are passing in this line

  action = "Search",

Which makes no sense to this line here

  "Cuisine/{name}",

In order of it to work you will need to either implement the {action} parameter, or simply remove it all together.

The reason for this is because you are stating that your url will look like Cuisine/{name} which means you will pass in a parameter called name with whatever value. However in your new statement you are including another parameter called action, which isn't understood by ASP because you haven't stated that it's part of the url. So ASP will look for Cuisine/{action}/{name} and when you pass in just Cuisine/{name} it won't understand what to do.

Upvotes: 1

Related Questions