我正在尝试通过默认路由中的id参数从我的数据库中检索数据:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
在这个ActionResult中,我试图基于route id参数呈现自定义用户控件,以便检索所请求页面的相关数据
public ActionResult InitPageNav(int id)
{
PageModel page = PageNavHelper.GetPageByID(id);
return PartialView("UserControls/_PageNavPartial", page);
}
编辑*
public static MvcHtmlString CreateMenuItems(this HtmlHelper helper, string action, string text)
{
var menuItem = new TagBuilder("li");
var link = new TagBuilder("a");
//Get current action from route data
var currentAction = (string)helper.ViewContext.RouteData.Values["action"];
link.Attributes.Add("href", string.Format("/Home/{0}", action));
if (currentAction == action)
{
menuItem.AddCssClass("selected");
link.Attributes.Remove("href");
link.Attributes.Add("href", string.Format("/Home/{0}", currentAction.ToString()));
}
link.SetInnerText(text);
menuItem.InnerHtml = link.ToString();
return MvcHtmlString.Create(menuItem.ToString());
}
但我一直收到错误:
参数字典包含非可空类型的参数“id”的空条目
谁能发现我哪里出错?
解决方法:
要调用该操作,URL中需要一个整数,如下所示:/ Home / InitPageNav / 1
或者你改变动作方法以允许可以为空的整数(但这没有意义,除非你有一个默认页面,如果没有给出id,你可以检索它).
如果您不想在网址中使用网页ID,则需要其他内容来标识网页,例如标题?
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{title}", // URL with parameters
new { controller = "Home", action = "Index", title = UrlParameter.Optional } // Parameter defaults
);
和行动:
public ActionResult InitPageNav(String title)
{
PageModel page = PageNavHelper.GetPageByTitle(title);
return PartialView("UserControls/_PageNavPartial", page);
}
只需确保处理title参数为空/ null的情况.通常,您应该使用Mvc框架中已存在的帮助器/扩展来构建您的URL.
@Html.ActionLink("Link text", "action", "controller", new { title = "whatever" }, null)
或者在你的高级助手中,
public static MvcHtmlString CreateMenuItems(this UrlHelper url, string action, string text)
{
var menuItem = new TagBuilder("li");
var link = new TagBuilder("a");
//Get current action from route data
var currentAction = (string)helper.RequestContext.RouteData.Values["action"];
link.Attributes.Add("href", url.Action(action, "home", new { title = "whatever" }));
if (currentAction == action)
{
menuItem.AddCssClass("selected");
}
link.SetInnerText(text);
menuItem.InnerHtml = link.ToString();
return MvcHtmlString.Create(menuItem.ToString());
}