2011-09-30 302 views
0

我在我的网站上有为前端创建/编辑/删除页面的功能。这里是我的控制器:创建Html.ActionLink到动态内容页面

namespace MySite.Controllers 
{ 
    public class ContentPagesController : Controller 
    { 
     readonly IContentPagesRepository _contentPagesRepository; 

     public ContentPagesController() 
     { 
      MyDBEntities entities = new MyDBEntities(); 
      _contentPagesRepository = new SqlContentPagesRepository(entities); 
     } 


     public ActionResult Index(string name) 
     { 
      var contentPage = _contentPagesRepository.GetContentPage(name); 

      if (contentPage != null) 
      { 
       return View(new ContentPageViewModel 
       { 
        ContentPageId = contentPage.ContentPageID, 
        Name = contentPage.Name, 
        Title = contentPage.Title, 
        Content = contentPage.Content 
       }); 
      } 

      throw new HttpException(404, ""); 
     } 
    } 
} 

而且在我的Global.asax:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     "Page", // Route name 
     "Page/{name}", // URL with parameters 
     new { controller = "ContentPages", action = "Index" }, // Parameter defaults 
     new[] { "MySite.Controllers" } 
    ); 

    routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults 
     new[] { "MySite.Controllers" } 
    ); 
} 

所以我有一个动态的网页在我的数据库,命名关于。如果我转到mysite.com/Page/About,我可以查看动态内容。

我想创建一个ActionLink到这个页面。我试着这样说:

@Html.ActionLink("About Us", "Index", "ContentPages", new { name = "About" }) 

但是,当我看到页面上的链接,链接只是去到当前页面的查询字符串Length=12。例如,如果我在主页上,链接将转到mysite.com/Home?Length=12

我在这里做错了什么?

回答

2

您没有使用正确的ActionLink重载。试试这样:

@Html.ActionLink(
    "About Us",    // linkText 
    "Index",     // action 
    "ContentPages",   // controller 
    new { name = "About" }, // routeValues 
    null      // htmlAttributes 
) 

,而在你的榜样:

@Html.ActionLink(
    "About Us",    // linkText 
    "Index",     // action 
    "ContentPages",   // routeValues 
    new { name = "About" } // htmlAttributes 
) 

这很明显地解释了为什么你不会产生预期的链接。