C# 实现博客条目链接
我正在开发一个类似博客引擎的应用程序。在主页的视图中,我有一个链接C# 实现博客条目链接,c#,asp.net,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc 4,我正在开发一个类似博客引擎的应用程序。在主页的视图中,我有一个链接 <a href="/Blog/BlogEntry/2013/05/22/title for this blog entry" /> 问题是我如何做到这一点?这样做,因为所有参数都将从URL映射。使用操作筛选器以所需的方式映射数据。我没有完全测试代码,但它会给票价的想法。将此属性添加到操作上方 public ActionResult BlogEntry(int year, int month , int day
<a href="/Blog/BlogEntry/2013/05/22/title for this blog entry" />
问题是我如何做到这一点?这样做,因为所有参数都将从URL映射。使用操作筛选器以所需的方式映射数据。我没有完全测试代码,但它会给票价的想法。将此属性添加到操作上方
public ActionResult BlogEntry(int year, int month , int day , string title)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace OurAttributes
{
public class PopulateTitleDandDateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string[] url = filterContext.HttpContext.Request.Uri.split('/');
DateTime d = new Date(url[2],url[3],url[4]);
if (filterContext.ActionParameters.ContainsKey("createdDate"))
{
filterContext.ActionParameters["createdDate"] = d;
}
if (filterContext.ActionParameters.ContainsKey("title"))
{
filterContext.ActionParameters["title"] = url[5] ;
}
base.OnActionExecuting(filterContext);
}
}
}
正如Devesh建议的那样,我修改了他的代码中的某些内容,并且成功了
- 控制器:
[HttpGet] [PopulateTitleDandDate] public ActionResult BlogEntry(string title, DateTime createdDate) { var viewModel = new BlogEntryModel { Tittle = title, CreatedDate = createdDate }; return View(viewModel); }
- PopulateTitleAndDateAttribute
public class PopulateTitleDandDateAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var url = filterContext.HttpContext.Request.RawUrl.Split('/'); if (url.Length >= 7) // TODO: it is actually not good here { var d = new DateTime(url[3].ConvertToInteger(), url[4].ConvertToInteger(), url[5].ConvertToInteger()); if (filterContext.ActionParameters.ContainsKey("createdDate")) { filterContext.ActionParameters["createdDate"] = d; } if (filterContext.ActionParameters.ContainsKey("title")) { filterContext.ActionParameters["title"] = url[6]; } } base.OnActionExecuting(filterContext); } }
- BlogEntry.cshtml
@model SampleApplication.Controllers.BlogEntryModel <h2>@Html.Raw(Model.Tittle) (@Html.Raw(Model.CreatedDate))</h2>
@model SampleApplication.Controllers.BlogEntryModel @Html.Raw(Model.title)(@Html.Raw(Model.CreatedDate))
再次感谢Devesh。感谢您的评论。但是我想提交到BlogEntry(字符串标题,DateTime createdDate)之类的函数。这是我的要求。@ThangChung我已经更新了我的解决方案,以使用actionfilter来填充CreatedDate和标题。请看一看。
@model SampleApplication.Controllers.BlogEntryModel
<h2>@Html.Raw(Model.Tittle) (@Html.Raw(Model.CreatedDate))</h2>