【问题标题】:how to write url in asp.net mvc如何在asp.net mvc中写入url
【发布时间】:2014-01-06 09:45:55
【问题描述】:

我想在 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);
    }

【问题讨论】:

  • 当前的网址是什么样的? item.heading的内容是什么,是如何生成的?

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing url-routing


【解决方案1】:

你可以用这个方法;

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)

【讨论】:

  • 我必须在控制器类或其他任何地方添加此功能?
  • 您可以在应用程序中创建一个名为 helper 的类。
  • 如何从我的控制器方法中调用 Html Helper 方法?简单地使用静态类 HtmlHelper 是行不通的。
  • 你应该在你的视图中使用你的帮助类而不是控制器。
  • 谢谢它的工作..但是这样做我遇到了另一个问题“页面请求是错误请求”,我正在按 ID 而不是页面名搜索记录,然后我也遇到了同样的问题跨度>
猜你喜欢
  • 2014-09-26
  • 1970-01-01
  • 2017-04-27
  • 2023-03-15
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 2011-08-24
  • 2013-08-28
相关资源
最近更新 更多