当我将浏览器导航到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
发现此错误
参数字典包含参数'id'的空条目 方法的非可空类型'System.Int32' 'System.Web.Mvc.ActionResult ViewAd(Int32)'中 'Youe3lan.Controllers.RealEstatesController'。可选参数 必须是引用类型,可空类型,或声明为 可选参数。 参数名称:参数
这是我的控制器:
namespace MvcAppliction1.Controllers
{
public class RealEstatesController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ViewAd(int id)
{
return View();
}
public ActionResult CreateAd()
{
return View();
}
}
}
答案 0 :(得分:1)
您需要将其更改为:
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
<强>更新强>
将此添加到您的控制器:
public ActionResult ViewAd(Int32 id)
{
return View();
}
你看
本地主机:10793 / RealEstates / 10
被翻译为:
本地主机:10793 / RealEstates / ViewAdd / 10
所以你需要在控制器中接受一个it参数的方法。
答案 1 :(得分:0)
您已将路线中的ID标记为可选:
id = UrlParameter.Optional
但我打赌你的控制器不可空?
public ActionResult ViewAd(Int32 id)
{
}
所以即使路由允许,你也无法在你的id中发布null。如果您将其更改为:
public ActionResult ViewAd(Int32? id)
{
}
您将不会收到错误消息:
参数字典包含参数'id'的空条目 方法的非可空类型'System.Int32' 'System.Web.Mvc.ActionResult ViewAd(Int32)'中 'Youe3lan.Controllers.RealEstatesController'。可选参数 必须是引用类型,可空类型,或声明为 可选参数。参数名称:参数