我正在从数据库中提取剃刀视图的标记,详见此问题:
ASP.NET MVC load Razor view from database
我可以拉取视图,但由于无法识别ViewBag,因此无法执行。
CS0103:当前上下文中不存在名称“ViewBag”
有什么建议吗?
这是来源:
全局:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(new BearForce.Web.Core.DbPathProvider());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
我的路径提供者:
namespace BearForce.Web.Core
{
public class DbPathProvider : VirtualPathProvider
{
public DbPathProvider()
: base()
{
}
public override bool FileExists(string virtualPath)
{
var repo = new Repository();
var viewPage = repo.GetView(240, virtualPath);
if (base.FileExists(virtualPath))
{
return true;
}
if (viewPage != null)
{
return true;
}
return false;
}
public override VirtualFile GetFile(string virtualPath)
{
if (base.FileExists(virtualPath))
{
return base.GetFile(virtualPath);
}
var repo = new Repository();
var result = repo.GetView(240, virtualPath);
var vf = new DbVirtualFile(virtualPath, result.Markup);
return vf;
}
}
}
我的虚拟文件:
public class DbVirtualFile : System.Web.Hosting.VirtualFile
{
string _fileContents = string.Empty;
public DbVirtualFile(string path, string fileContents)
: base(path)
{
_fileContents = fileContents;
}
public override System.IO.Stream Open()
{
return new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(_fileContents));
}
}
我的控制器:
public ActionResult Index()
{
ViewBag.Title = "aaah!!! Muppets!!! Help!!!!!";
return View();
}
显然,这是概念的证明,所以这些名字都很愚蠢,代码也很邋...... ......
答案 0 :(得分:18)
对于遇到此错误的未来人员,如果您的“视图”和根项目文件夹中缺少web.config文件,则可能会出现此错误。
答案 1 :(得分:4)
您应该确保您要返回的视图对应于剃刀视图。这是一个简化的工作示例:
public class CustomPathProvider : VirtualPathProvider
{
private class CustomVirtualFile : VirtualFile
{
public CustomVirtualFile(string path)
: base(path)
{ }
public override Stream Open()
{
return new MemoryStream(Encoding.UTF8.GetBytes("Hello @ViewBag.Name"));
}
}
public override bool FileExists(string virtualPath)
{
// This is very important: make sure that here you
// are returning true only for Razor view pages or
// you won't have ViewBag.
// In this oversimplified example we support
// the index view for the home controller
return virtualPath == "/Views/Home/Index.cshtml";
}
public override VirtualFile GetFile(string virtualPath)
{
return new CustomVirtualFile(virtualPath);
}
}
将在Application_Start
注册:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
HostingEnvironment.RegisterVirtualPathProvider(new CustomPathProvider());
}
最后是一个样本控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Name = "John";
return View();
}
}
如果您要实施自定义VirtualPathProvider,那么这是最后一个非常重要的评论:
如果您的Web应用程序已预编译,则不起作用。因此,如果您正在使用预编译(例如发布...或Web部署项目),则永远不会使用自定义虚拟路径提供程序。