.NET - URL Routing

24.02.2015

Zde je jednoduchý příklad (bez dalšího komentáře) jak použít URL routing.

Global.asax

void Application_Start(object sender, EventArgs e) {
    addRoute(RouteTable.Routes);
}

public static void addRoute(RouteCollection routes) {
    routes.MapPageRoute("Home", "home", "~/default.aspx");
    // RoutName,RoutedLink,page link

    routes.MapPageRoute("Products", "product/{prdc_id}/{prdc_name}", "~/product.aspx");
}

Default.aspx

protected void Page_Load(object sender, EventArgs e) {
    RouteValueDictionary prm = new RouteValueDictionary();
    prm.Add("prdc_name", UrlCleaner("produkt 1"));    
    // add route data values which is procduct name

    prm.Add("prdc_id", 1);
    // add route data values which is product ID

    VirtualPathData path = RouteTable.Routes.GetVirtualPath(null, "Products", prm);
    // Add route name and route data

    HyperLink1.NavigateUrl = path.VirtualPath;
    // give hyperlink to virtual path
}

public static string UrlCleaner(string myText) {
    string text = myText;
    text = textReplace(".", "");
    text = textReplace("'", "");
    text = textReplace(" ", "-");
    text = textReplace("<", "");
    text = textReplace(">", "");
    text = textReplace("&", "");
    text = textReplace("[", "");
    text = textReplace("]", ""); return text;
}

Product.aspx

protected void Page_Load(object sender, EventArgs e) {
    if (RouteData.Values["prdc_name"] != null && RouteData.Values["prdc_id"] != null) {
        lbl_productID.Text = RouteData.Values["prdc_id"].ToString();
        lbl_productname.Text = UrlCleaner(RouteData.Values["prdc_name"].ToString());
    } else {
    Response.Redirect("~/Home");
    }
}

public static string UrlCleaner(string MyText) {
    string text = MyText;
    text = text.Replace("-", " ");
    return text;
}

© 2020 Olda Zátopek
Vytvořeno službou Webnode
Vytvořte si webové stránky zdarma! Tento web je vytvořený pomocí Webnode. Vytvořte si vlastní stránky zdarma ještě dnes! Vytvořit stránky