我正在开发像博客引擎这样的应用程序。在主页视图中,我有一个链接
<a href="/Blog/BlogEntry/2013/05/22/title for this blog entry" />
当用户点击该链接时,它将转到Blog控制器并在那里运行BlogEntry操作
public class BlogController : Controller {
public ActionResult BlogEntry(string title, DateTime createdDate) {
// doing something
var viewModel = something here for build the view model
return View(viewModel);
}
}
问题是我该怎么做?
答案 0 :(得分:2)
这样做,因为所有参数都将从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);
}
}
}
答案 1 :(得分:1)
正如Devesh的建议,我在他的代码中修改了一些东西,并且它有效
控制器:
[HttpGet]
[PopulateTitleDandDate]
public ActionResult BlogEntry(string title, DateTime createdDate)
{
var viewModel = new BlogEntryModel
{
Tittle = title,
CreatedDate = createdDate
};
return View(viewModel);
}
PopulateTitleDandDateAttribute
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>
再次感谢Devesh。