Mist
Mist

Reputation: 684

ASP.Net MVC: Routing issue which throwing exception

I have a test controller where i have one index action which accept custid as a argument.

this is how my controller looks

public class TestController : Controller
{
    // GET: Test
    public ActionResult Index(int custid)
    {
        return View();
    }
}

i have added one extra routing statement in route.config file.

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

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

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

so when accessing test controller action with url like localhost:50675/test/101 then getting error. error message say

The parameters dictionary contains a null entry for parameter 'custid' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'WebAPICRUD.Controllers.TestController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

but when accessing test controller action with url like localhost:50675/test?custid=101 then getting no error.

so i do not understand what mistake is there in code.

What i need to do as a result i can issue this url http://localhost:50675/test/101 which should work. please guide me. thanks

Upvotes: 1

Views: 485

Answers (1)

user3559349
user3559349

Reputation:

Your route definition need to contain a segment for custid (not id) to match the name of the parameter. The route definition should also contain the name of the controller to make it unique

routes.MapRoute(
    name: "custom1",
    url: "Test/{custid}", // modify
    defaults: new { controller = "Test", action = "Index"}
);

Note that you can also remove the custid = UrlParameter.Optional since you do not want it to be optional

Upvotes: 2

Related Questions