FindView not working properly
I have a helper class that I use to create and send "HTML Emails". this class is in my web/Infrastructure/Communication folder. I create a view in my project and I use FindView to find this view.
public Stream GetViewStream(string viewName, object model, ControllerContext context, ViewDataDictionary viewData, TempDataDictionary tempData)
{
var view = ViewEngines.Engines.FindView(context, viewName,"");
if (view == null)
{
throw new InvalidOperationException(string.Format("Could not find a view named '{0}'", viewName));
}
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
var viewContext = new ViewContext(context, view.View, viewData, tempData, writer);
view.Render(viewContext, writer);
writer.Flush();
}
return new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));
}
In my project I have an areas folder and each system has a folder and within these folders I have Models,Views and controllers.
now
my problem is when I use this method from my MailController it searches in web/Areas/Mail/Views for the view which is right but when I use this fr开发者_C百科om my AdvisoryController it searches for the view in web/Views.
how can I fix this and why is this happening?
If you poke around in the class VirtualPathProviderViewEngine
and in particular the method FindView
you'll see that it uses a method named GetPath
in order to get a path to search for views.
It turns out that unless you specify the path to the view (by using "~" or "/" as first letter), it will use the area name from the ControllerContext
.
This means that you either have to manipulate the controller context before looking up your view, or that you specify the view yourself.
You can mess around with the view location path's in the view engine upon initialization of the same, but I think that would invite more problems than it would solve.
精彩评论