0
我安裝我的路由,使我有以下的平板URL結構:MVC映射路線導航菜單,避免硬編碼鏈路
mywebsite/service-option-one (goes to Home Controller, Option1 action)
mywebsite/service-option-two (goes to Home Controller, Option2 action)
mywebsite/ (goes to Home Controller, Index)
mywebsite/about (goes to Home Controller, Index with path=about)
mywebsite/contact (goes to Home Controller, Index with path=contact)
這是重要的,因爲我有很多的內容的意見和做不希望對這些通用信息頁面進行單獨的操作,解析視圖的簡單代碼在本文後面。
建立菜單時,MVC Html.ActionLink
助手,但他們給不正確的通用內容的地址,因爲這些操作不存在!
鑑於我的地址方案,如何可以使用輔助方法來設置我的錨鏈接目標,或者我只需要在html中使用硬編碼(即<a href="~/contact>Contact us</a>
)?
// note that the order of the routes is very important!
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// error route
routes.MapRoute(
"Error", // Route name
"Oops", // URL with parameters
new { controller = "Home", action = "Error" }
);
routes.MapRoute(
"Service1",
"service-option-one",
new { controller = "Home", action = "Option1" }
);
routes.MapRoute(
"Service2",
"service-option-two",
new { controller = "Home", action = "Option1" }
);
// default home controller route for general site content (/content), uses default path value set to Index
routes.MapRoute(
name: "Catchall",
url: "{path}",
defaults: new { controller = "Home", action = "Index", path = "Index" }
);
// home page route, blank url (/)
routes.MapRoute(
"HomePage", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" }
);
// default route
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "{controller}", action = "{action}", id = UrlParameter.Optional } // Parameter defaults
);
}
public class HomeController : Controller
{
private bool ViewExists(string name)
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
return (result.View != null);
}
public ActionResult Index(string path)
{
System.Diagnostics.Debug.WriteLine("looking for..." + path);
if (ViewExists(path)==true)
{
System.Diagnostics.Debug.WriteLine("general controller action...");
return View(path);
}
else
{
System.Diagnostics.Debug.WriteLine("page not found...");
return RedirectToRoute("Error");
}
}
public ActionResult Error()
{
return View();
}
public ActionResult Option1()
{
return View();
}
public ActionResult Option2()
{
return View();
}
}