I have a web page www.example.com which points to a HomeController index. When I run the website I get the HomeView.
Now the requirement is when I type www.example.com/Japan I need to run a different view.
What I did:
public ActionResult Index(string country)
{
ViewBag.Message = "my country=" + country;
return View();
}
But it gives me an error:
The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index() on type MvcApplication_2.Controllers.HomeController System.Web.Mvc.ActionResult Index(System.String) on type MvcApplication_2.Controllers.HomeController
What should I be doing to achieve this one?
I do not want to use http://example.com/country/japan.
I want to use http://example.com/japan.
my code: RouteConfig.cs
namespace MvcApplication_2
{
public class RouteConfig
{
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: "ByCountry",
url: "{country}",
defaults: new { controller = "Home", action = "IndexByCountry" }
);
}
}
}
Homecontroller.cs
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
[ActionName("IndexByCountry")]
public ActionResult Index(string country)
{
ViewBag.Message = "Japan man.";
return View("Index");
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
ByCountry
route before theDefault
route. Switch up that order so the default route is last. – Thomas Stringer