我試圖讓我的網站看起來很好,並與slu se友好。我想我已經成功了,但後來我的默認路由停止工作。 當我去這個example.com/location/viewlocation/528然後url結束像example.com/528/a-nice-location使用slug和id的MVC url路由。使默認路由混亂
所以,這很好! 但現在我的正常東西dosent工作。 打字在錯誤example.com/home/index結果
參數字典包含參數非空類型「System.Int32」的「ID」爲方法「System.Web.Mvc一個空條目在'Oplev.Controllers.LocationController'中的.ActionResult ViewLocation(Int32,System.String)'。可選參數必須是引用類型,可爲空類型,或者聲明爲可選參數。
我已經嘗試了不同的解決方案,但我失去了一些東西。無法讓它工作。
我的代碼: RouteConfig
routes.MapRoute(
name: "view_location",
url: "{id}/{slug}",
defaults: new { controller = "Location", action = "ViewLocation", id = UrlParameter.Optional, slug = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
位置控制器
public ActionResult ViewLocation(int id, string slug)
{
if (string.IsNullOrEmpty(slug))
{
slug = "a-nice-location"; // testing..
return RedirectToRoute("view_location", new { id = id, slug = slug });
}
return View();
}
Home控制器
public ActionResult Index()
{
return View();
}
在必要
Route
屬性或者你可以使用'INT?'類型,而不是'int'。該消息很簡單:如果您使用的是非空類型,則需要爲路由聲明數值約束。 –