带有ControllerName / ExampleID的ASP.NET MVC URL路由
当我将浏览器导航到网址时,出现此错误:
localhost:10793/RealEstates/10
这是我的RouteConfig代码:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Main", action = "Index" }
);
routes.MapRoute(
name: "RealEstates",
url: "RealEstates/{action}",
defaults: new { controller = "RealEstates", action = "Index" }
);
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id = UrlParameter.Optional }
);
}
}
我的错误:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
将代码更改为:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}",
// defaults: new { controller = "Main", action = "Index" }
//);
//routes.MapRoute(
// name: "RealEstates",
// url: "RealEstates/{action}",
// defaults: new { controller = "RealEstates", action = "Index" }
//);
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id = UrlParameter.Optional }
);
}
}
它的工作,但当我呼吁在控制器中的其他行动
本地主机:10793 / RealEstates / CreateAd
发现这个错误
参数字典包含'Youe3lan.Controllers.RealEstatesController'中方法'System.Web.Mvc.ActionResult ViewAd(Int32)'的非空类型'System.Int32'的参数'id'的空项。 可选参数必须是引用类型,可为空类型,或者声明为可选参数。 参数名称:参数
而这个我的控制者:
namespace MvcAppliction1.Controllers
{
public class RealEstatesController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ViewAd(int id)
{
return View();
}
public ActionResult CreateAd()
{
return View();
}
}
}
您需要将其更改为:
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{action}/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id UrlParameter.Optional }
);}}
看看这可能会有所帮助:
http://msdn.microsoft.com/en-us/library/cc668201(v=vs.100).aspx
UPDATE
将此添加到您的控制器中:
public ActionResult ViewAd(Int32 id)
{
return View();
}
你看
本地主机:10793 / RealEstates / 10
被翻译为:
本地主机:10793 / RealEstates / ViewAdd / 10
所以你需要在控制器接受它的参数的方法。
您已将您的身份证在您的路线中标记为可选:
id = UrlParameter.Optional
但我敢打赌你的控制器不是空的?
public ActionResult ViewAd(Int32 id)
{
}
所以即使路由允许,你也不能在你的ID中发布null。 如果您将其更改为:
public ActionResult ViewAd(Int32? id)
{
}
您将不会收到错误消息:
参数字典包含'Youe3lan.Controllers.RealEstatesController'中方法'System.Web.Mvc.ActionResult ViewAd(Int32)'的非空类型'System.Int32'的参数'id'的空项。 可选参数必须是引用类型,可为空类型,或者声明为可选参数。 参数名称:参数
链接地址: http://www.djcxy.com/p/39225.html上一篇: ASP.NET MVC URL Routing with ControllerName/ExampleID
下一篇: creating Controller Action CreateNewEmployee in Northwind DB