check second parameter in asp.net

Viewed 52

I am new in c# mvc, and I am trying to make a route with multiple parameters that looks like this:

controller/action/parameterOne/parameterTwo

but in some cases I'm gonna just use one of them so the route will look like this:

controller/action/parameterOne

here is my RouteConfig.cs

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

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name:"Default2",
            url: "{controller}/{action}/{category}/{id}",
            defaults: new { controller = "Home", action = "Index", category = UrlParameter.Optional, id = UrlParameter.Optional }
        );
    }

now in my controller's action I need to check if there is only one parameter or two so I can return a different view for each condition, here is the controller:

[HttpGet]
    public ActionResult someAction(string category, string id)
    {
        if (String.IsNullOrWhiteSpace(id))
        {
                return View("viewOne");
        }
        else
        {
            return View("ViewTwo");
        }
    }

the problem is that the if statement is not full working? because if the conditoin is this: String.IsNullOrWhiteSpace(id)

and if I write controller/action/parameterOne this return the ViewOne

but if I write controller/action/parameterOne/parameterTwo also return the ViewOne

but now if a invert the condition and I write !String.IsNullOrWhiteSpace(id) both urls return ViewTwo.

So does any one have any idea why is that happening?

1 Answers

Do you have any objection to only using the default route? The only drawback that comes to mind is if you really want your url to look a certain way in which case you may need to define multiple routes as youre trying to do. However, the following should work with only the default route:

//note controller actions will default to HttpGet if no data annotation is explicitly supplied. Also, action names generally begin uppercase by convention
public ActionResult SomeAction(string category, string id = null)
{
    if (String.IsNullOrWhiteSpace(id))
    {
        return View("viewOne");
    }
    else
    {
        return View("ViewTwo");
    }
}

the various requests you mentioned would look like:

www.myhost.com/controller/someaction?category=parameterOne&id=parameterTwo

or

www.myhost.com/controller/someaction?category=parameterOne

Related