How to create UrlSlug in Asp.Net MVC

转自:http://www.ehsanghanbari.com/Post/20/how-to-create-urlslug-in-aspnet-mvc

UrlSlug Is a way of generating a valid Url, and using the
title of an article to generate a URL. UrlSlug is very important in CEO because
google likes to index the meaningful Urls at the first and then it refers to
other Urls. Spouse you wanna to create the this Url:

  1. MyWebSite.com/Blog/Post/2013/4/14/how-to-create-url-slug-in-aspnet-mvc

create the model class :


public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string PostSlug { get; set; }
public DateTime CreationTime { get; set; }
}

Now to creating the UrlSlud you have to call a function, you
can create it as an extension method like this:


public static class SlugGeneratorHelper
{
public static string GenerateSlug(
this string phrase, int maxLength = 100)
{
string str = phrase.ToLower();
str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
str = Regex.Replace(str, @"[\s-]+", " ").Trim();
str = str.Substring(0, str.Length <= maxLength ?
str.Length : maxLength).Trim();
str = Regex.Replace(str, @"\s", "-");
return str;
}
}

Now it‘s time to use this extension method, create the
CreatePost action and use the
GenerateSlug


public ActionResult CreatePost()
{
return View("CreatePost");
}

[HttpPost]
public ActionResult CreatePost(Blog blog)
{
if (ModelState.IsValid)
{
_blogService.CreateBlogPost(blog);
blog.PostSlug = blog.Title.GenerateSlug();
}
return View("CreatePost");
}

You craeted the postSlug, now about how to use and show it in
URL look at the action below


public ActionResult Post(int year, int month, int day, string postSlug)
{
var post = _blogService.GetBlogPostByDate(year,month,day,postSlug);
return View("Post", post);
}

GetBlogPostByDate is a method that you can
define in your repository to get the post by year, month , day and postSlug ;
something like this:


public Blog GetBlogPostByDate (int year, int month, int day,string postSlug)
{
var query =
_dbContextConfiguration.Blog.Where(
p => p.CreationTime.Year == year && p.CreationTime.Month == month && p.CreationTime.Day == day&&p.PostSlug==postSlug);

return query.Single();
}

Finally register this route in your global.


asax

routes.MapRoute("BlogRoute",
"Post/{year}/{month}/{day}/{postSlug}",
new
{
controller = "Blog",
action = "Post",
year = UrlParameter.Optional,
month = UrlParameter.Optional,
day = UrlParameter.Optional,
newsSlug = ""
},
new[] { "SampleProject.Web.Mvc.UI.Controllers" });

You have done, test it!

时间: 2024-10-13 05:25:39

How to create UrlSlug in Asp.Net MVC的相关文章

[webgrid] &ndash; selecterow - (Get Selected Row from ASP.NET MVC 3 WebGrid)

Get Selected Row from ASP.NET MVC 3 WebGrid Abstract: The following article demonstrates how to get the selected row from the ASP.NET MVC 3 WebGrid and what to do to display data. Every website has to display data and every website has a Grid control

[转]Load ASP.NET MVC Partial Views Dynamically Using jQuery

本文转自:http://www.binaryintellect.net/articles/218ca630-ba50-48fe-af6e-6f754b5894aa.aspx Most of the times ASP.NET MVC views are rendered as a result of user  navigating to some action. For example, when a user navigates to /home/index in  the browser

ASP.NET MVC 使用Remote特性实现远程属性验证

RemoteAttribute是asp.net mvc 的一个验证特性,它位于System.Web.Mvc命名空间 下面通过例子来说明 很多系统中都有会员这个功能,会员在前台注册时,用户名不能与现有的用户名重复,还要求输入手机号码去注册,同时手机号码也需要验证是否重复,下面是实体类 /// <summary> /// 会员 /// </summary> public class Member { public int Id { get; set; } [Required(Error

CRUD Operations In ASP.NET MVC 5 Using ADO.NET

Background After awesome response of an published by me in the year 2013: Insert, Update, Delete In GridView Using ASP.Net C#. It now has more than 140 K views, therefore to help beginners I decided to rewrite the article i with stepbystep approach u

ASP.NET MVC验证框架中关于属性标记的通用扩展方法

http://www.cnblogs.com/wlb/archive/2009/12/01/1614209.html 之前写过一篇文章<ASP.NET MVC中的验证>,唯一的遗憾就是在使用Data Annotation Validators方式验证的时候,如果数据库是Entityframework等自动生成的文件,就没有办法使用扩展属性标记进行标记.现在已经开始有了一些其它的Asp.net MVC 验证框架,使用上跟Data Annotation Validators差不太多,但是普遍有这样

[渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序读取相关数据

这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第六篇:为ASP.NET MVC应用程序读取相关数据 原文:Reading Related Data with the Entity Framework in an ASP.NET MVC Application 译文版权所有,谢绝全文转载--但您可以在您的网站上添加到该教程的链接. 在之前的教程中您已经完成了学校数据模型.在本教程中你将

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W

ASP.NET MVC 4 (五) 视图

视图引擎与视图 多数情况下控制器action方法返回ViewResult对象,MVC内建action调用器ControllerActionInvoker负责调用控制器action方法并调用视图引擎处理ViewResut,由视图引擎将ViewResult转化为ViewEngineResult对象,ViewEngineResult对象内含实现IView接口的视图对象,最终MVC框架调用视图对象的Render的方法渲染输出结果.下面还是以例子来演示这个过程,先来看看相关接口和类的定义与实现: publ

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo

1.JQueryEasyUI使用 JQuery EasyUI中文官网:http://www.jeasyui.net/ JQuery EasyUI中文官网下载地址:http://www.jeasyui.net/download/ jQuery EasyUI 1.4 版 API 中文版: 链接:http://pan.baidu.com/s/1c1pAutE%20 密码:0mk8 JQuery EasyUI 1.4.4 百度云盘:链接:http://pan.baidu.com/s/1bnRpH3T 密