I created two action methods with a different name in the home controller
public ActionResult Default()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View("index");
}
public ActionResult Index(int a)
{
ViewData["Message"] = "Welcome to ASP.NET MVC! and Your Age is " + a;
return View();
}
And my routing code look like:
routes.MapRoute(
"Default1", // Route name
"{Home}/{ID}", // URL with parameters
new { controller = "Home", action = "Index", id =UrlParameter.Optional});
routes.MapRoute(
"Default2", // Route name
"{Home}", // URL with parameters
new { controller = "Home", action = "Default" }
);
routes.MapRoute(
"Default", // Route name
"{controller}", // URL with parameters
new { controller = "Home", action = "Default" }
);
But still getting problem
when I type URL like http://localhost:7221 then home is coming and Default() method invoking but if I type URL like
http://localhost:7221/Home then getting error. to handle this situation i define route like
routes.MapRoute(
"Default2", // Route name
"{Home}", // URL with parameters
new { controller = "Home", action = "Default" }
);
But it is not working…….can u tell me why.
If I type URL like http://localhost:7221/Home/88 then Index(int a) method should be called but getting error. why
I want that when I type URL http://localhost:7221 or http://localhost:7221/Home then Default() should be called and when I will type
http://localhost:7221/Home/88 then Index(int a) should be invoked. What is wrong in my route? How can I rectify it? if possible rectify my route code. thanks
The reason why you are having problems is that your routeparameters don’t match with the action method. Your action method requires int a, yet you are not providing it in any case, you are giving integer called id.
What you should have in routevalues is:
Note how age parameter is optional. Our controller should then look like this:
Ofcourse we could use parameter called id but I called it age for demonstration purposes.
Update:
Here’s something closer to your original request:
Controller: