簡體   English   中英

如何在asp.net mvc中編寫url

[英]how to write url in asp.net mvc

我想在url中的單詞之間添加“ - ”或“+”。 例如url像:

http://localhost/bollywood/details/23-abhishek-back-from-dubai-holiday.htm

我的路線模式是

routes.MapRoute(
            name: "AddExtension",
            url: "{controller}/{action}/{id}-{title}.htm",
            defaults: new { controller = "Bollywood", action = "Details" }
        );

我在我的視圖上創建了這樣的鏈接:

@Html.ActionLink(item.n_headline, "Details", new { id = item.News_ID, title = item.n_headline.ToSeoUrl() }, htmlAttributes: null)

我的寶萊塢控制器在這里

public ActionResult Details(int? id, string controller, string action, string title)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        tblBollywood tblbolly = db.tblBollywood.Find(id);
        if (tblbollywood == null)
        {
            return HttpNotFound();
        }
        return View(tblbollywood);
    }

你可以使用這種方法;

public static string ToSeoUrl(this string url)
{
    // make the url lowercase
    string encodedUrl = (url ?? "").ToLower();

    // replace & with and
    encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");

    // remove characters
    encodedUrl = encodedUrl.Replace("'", "");

    // remove invalid characters
    encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9-\u0600-\u06FF]", "-");

    // remove duplicates
    encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");

    // trim leading & trailing characters
    encodedUrl = encodedUrl.Trim('-');

    return encodedUrl;
}

然后你可以用這種方式:

@Html.ActionLink(item.Name, actionName: "Category", controllerName: "Product", routeValues: new { Id = item.Id, productName = item.Name.ToSeoUrl() }, htmlAttributes: null)

編輯:

您需要創建一個新的自定義路線:

routes.MapRoute(
      "Page",
      "{controller}/{action}/{id}-{pagename}.htm",
      new { controller = "Home", action = "Contact" }
);

然后以這種方式使用ActionLink:

@Html.ActionLink("link text", actionName: "Contact", controllerName: "Home", routeValues: new { Id = item.id, pagename = item.heading.ToSeoUrl() }, htmlAttributes: null)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM