2012-11-22 35 views
3

我有路由問題。我的網站上有很多頁面是從數據庫動態生成的。如何在mvc3 web應用程序中設置特定路由

,我要完成的第一件事是路由到這些網頁那樣:

「如何修理汽車」

www.EXAMPLE.com/How-to-repair-a-car

現在它的工作原理類似:www.EXAMPLE.com/Home/Index/How-to-repair-a-car

其次我的默認頁必須是這樣的:www.EXAMPLE.com

在開始頁面將與pagging消息,所以如果有人在「第2頁」按鈕,單擊例如,地址應看:www.EXAMPLE.com/page = 2

結論:

  1. 默認頁面 - > www.EXAMPLE.com(含頁面= 0)
  2. 默認頁面與特定新聞頁面 - > www.EXAMPLE.com/page=12
  3. 文章頁面 - > www.EXAMPLE.com/如何修理汽車(沒有參數'頁面')路由sholud指向文章或錯誤404

PS:對不起,我的英語

+0

我不明白你的問題是什麼?請張貼您的路由代碼 – Curt

回答

1

嘗試在路由設置來創建文章路線,像一個基本的路由實例這樣的:

路由配置:

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

      routes.MapRoute(null, "{article}", 
          new {controller = "Home", action = "Article" }); 
      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
     } 
    } 

的HomeController:

public class HomeController : Controller 
    { 
     public ActionResult Index(int? page) 
     { 
      var definedPage = page ?? 0; 
      ViewBag.page = "your page is " + definedPage; 
      return View(); 
     } 

     public ActionResult Article(string article) 
     { 
      ViewBag.article = article; 
      return View(); 
     } 
    } 

/頁= 10 - ?工作

/如何對修理車 - 工程

這種做法優秀作品。

+0

非常感謝,這正是我想達到的。我還有一個小問題。我有什麼改變/?page = 10 to: www.EXAMPLE.com/p?page=1 – Ellbar

+1

什麼意思'p'(www.EXAMPLE.com/ ** p **?page = 1)in那種情況,這是行動嗎? – testCoder

+0

對不起,我的錯只是在你的回答中,謝謝:) – Ellbar

0

這裏是www.example.com/How-to-repair-car

using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing; 

namespace Tipser.Web 
{ 
    public class MyMvcApplication : HttpApplication 
    { 
     public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.MapRoute(
       "ArticleRoute", 
       "{articleName}", 
       new { Controller = "Home", Action = "Index", articleName = UrlParameter.Optional }, 
       new { userFriendlyURL = new ArticleConstraint() } 
       ); 
     } 

     public class ArticleConstraint : IRouteConstraint 
     { 
      public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
      { 
       var articleName = values["articleName"] as string; 
       //determine if there is a valid article 
       if (there_is_there_any_article_matching(articleName)) 
        return true; 
       return false; 
      } 
     } 
    } 
} 
相關問題