id-parameter of string type doesn't have optional attribute

Feb 7, 2015 at 9:55 PM
Hello.

I have a controller with string parameter on action method:
public class TestController : Controller
{
    public ActionResult GetSmth(string id)
    {
        if (String.IsNullOrEmpty(id))
            return Content("Empty");
        else
            return Content("NonEmpty");
    }
}
and routes registred as:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapCodeRoutes(
    typeof(DemoApp.Controllers.HomeController),
    new CodeRoutingSettings
    {
        UseImplicitIdToken = true
    }
);
It produces next line to the routes.axd output:
routes.MapRoute(null, "Test/GetSmth/{id}", new { controller = "Test", action = "GetSmth" }, new[] { "DemoApp.Controllers" });
I need the Empty content from the test controller, so I use:
@Url.Action("GetSmth", "~~Test")
but null returned instead of /Test/GetSmth

I think that because id = UrlParameter.Optional was not set to the route configuration.

If I use standard ASP.NET MVC routing mechanism, then Url.Action("GetSmth", "Test") works as expected (/Test/GetSmth url as result).
Coordinator
Feb 7, 2015 at 10:37 PM
Use a default value, e.g. string id = null or string id = "".
Marked as answer by eLVik on 2/8/2015 at 2:20 AM
Feb 8, 2015 at 9:26 AM
Thanks, Max.

Its works!
public class TestController : Controller
{
    public ActionResult GetSmth(string id = null)
    {
        if (String.IsNullOrEmpty(id))
            return Content("Empty");
        else
            return Content("NonEmpty");
    }
}
Marked as answer by eLVik on 2/8/2015 at 5:58 AM