基本上,我想知道是否有人知道你可以以一种首先寻找动作的方式设置MVC3的方式,如果不存在,它将自动返回该位置的视图。否则,每次创建页面时,我都必须在添加操作后重建它。
这不是阻止项目工作的问题,也不是问题,在代码中包含以帮助提高测试速度是一件非常好的事情。
编辑:
为了清楚起见,这是我每次创建一个内部没有任何逻辑的视图时所做的事情:
public ActionResult ActionX()
{
return View();
}
有时我会在动作中想要一些逻辑,但是对于空白页面的大部分时间我只想要上面的代码。
如果有任何方法总是为每个Controller / Action组合返回上面的代码,我想要它,除非我已经做了一个动作,然后它应该使用我指定的Action。
谢谢,
杰克
答案 0 :(得分:2)
为什么不为此创建单个操作。这将查找具有指定名称的视图,如果不存在则返回404。
[HttpGet]
public ActionResult Page(string page)
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, page, null);
if (result == null)
{
return HttpNotFound();
}
return View(page);
}
然后让你的默认路线回到这个:
routes.MapRoute("", "{page}", new { controller = "Home", action = "Page" });
因此,对http://yoursite.com/somepage的请求将调用Page(“somepage”)
答案 1 :(得分:1)
我并不完全确定这将是多么有用(或者它是否真的是一个好主意)但我猜你是否有纯静态内容的页面(但可能使用布局或其他东西,所以你不能使用静态html)它可能有用
无论如何,这是如何做到的(作为基类,但不一定是这样)
public abstract class BaseController : Controller
{
public ActionResult Default()
{
return View();
}
protected override IActionInvoker CreateActionInvoker()
{
return new DefaultActionInvoker();
}
private class DefaultActionInvoker : ControllerActionInvoker
{
protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
{
var actionDescriptor = base.FindAction(controllerContext, controllerDescriptor, actionName);
if (actionDescriptor == null)
actionDescriptor = base.FindAction(controllerContext, controllerDescriptor, "Default");
return actionDescriptor;
}
}
}