快捷搜索:

Asp.NET MVC Widget开发 - ViewEngine

在Asp.NET开拓博客类系统,我们常常都邑用到Widget,像在线石友、近来造访石友、最新留言等,关于Asp.NET MVC与Asp.NET视图的差异,这里不再说了,大年夜家可去查一下,接下来我以“我的石友”列表来要先容在Asp.NET MVC实现这一功能以及布局设计。

开拓对象:VS 2010 EN

开拓说话:Visual C#

ASP.NET MVC 3

关于ViewEngine这篇是Widgets实现的核心,这里必要自定义Asp.NET MVC的视图引擎,也便是让Asp.NET MVC视图引擎可以找到widgets中的文件。

直接造访会呈现以下差错,提示找不到显示文件

由差错中也可以看到 Asp.NET MVC默认引擎搜索文件的目录

/Views/Widget/

/Views/Shared/

要探求到"widgets"中的文件就必须要让视图引擎去"widgets"中搜索文件

如Friends: /widgets/Friends/

添加自定义视图引擎

1. 添加 "WidgetViewEngine.cs",承袭自BuildManagerViewEngine

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace Widgets

{

public class WidgetViewEngine : BuildManagerViewEngine

{

internal static readonly string ViewStartFileName = "_ViewStart";

public WidgetViewEngine()

: this(null)

{

}

public WidgetViewEngine(IViewPageActivator viewPageActivator)

: base(viewPageActivator)

{

AreaViewLocationFormats = new[] {

"~/Areas/{2}/Views/{1}/{0}.cshtml",

"~/Areas/{2}/Views/Shared/{0}.cshtml"

};

AreaMasterLocationFormats = new[] {

"~/Areas/{2}/Views/{1}/{0}.cshtml",

"~/Areas/{2}/Views/Shared/{0}.cshtml"

};

AreaPartialViewLocationFormats = new[] {

"~/Areas/{2}/Views/{1}/{0}.cshtml",

"~/Areas/{2}/Views/Shared/{0}.cshtml"

};

ViewLocationFormats = new[] {

"~/Views/{1}/{0}.cshtml",

"~/Views/Shared/{0}.cshtml"

};

MasterLocationFormats = new[] {

"~/Views/{1}/{0}.cshtml",

"~/Views/Shared/{0}.cshtml"

};

PartialViewLocationFormats = new[] {

"~/{1}s/{0}/Widget.cshtml",

"~/Views/{1}/{0}.cshtml",

"~/Views/Shared/{0}.cshtml"

};

FileExtensions = new[] {

"cshtml"

};

}

protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)

{

return new RazorView(controllerContext, partialPath,

layoutPath: null, runViewStartPages: false, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator);

}

protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)

{

var view = new RazorView(controllerContext, viewPath,

layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator);

return view;

}

}

}

您可能还会对下面的文章感兴趣: