【发布时间】:2014-06-27 16:09:00
【问题描述】:
我正在尝试在我的控制器和我的视图之间创建另一个层,以便我可以根据他们所属的公司的“客户 ID”将不同版本的视图传递给用户。
我有以下代码:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
// set client
var client = new Client();
client.Id = Guid.NewGuid();
client.Name = "Foo";
// set user
var user = new User();
user.Id = Guid.NewGuid();
user.ClientId = client.Id;
user.Name = "Foo";
return ViewRenderer.RenderView("AddComplete", client);
}
}
我的 ViewRenderer 类如下所示:
public static class ViewRenderer
{
public static ViewResult RenderView(string view, Guid clientId)
{
string viewName = GetViewForClient(view, clientId);
return Controller.View(view);
}
public static string GetViewForClient(string view, Guid clientId)
{
// todo: logic to return view specific to the company to which a user belongs...
}
}
问题是,RenderView(string view, Guid clientId) 中的 return Controller.View(view); 行给了我错误:
System.Web.Mvc.Controller.View()' 是不可访问的,因为它 防护等级
我很想知道如何解决这个错误,或者是否有更好的方法来做我想做的事情,即显示特定于用户所在公司的不同版本的视图属于。
编辑:我脑子里想的另一个选择...
有没有办法覆盖View() 方法,这样我就可以在它前面加上一个目录名称,例如,属于“Acme Co.”的用户。会像 View("MyView") 那样调用与其他所有人相同的控制器操作,但该方法实际上会调用 View("AcmeCo/MyView") 但是,我实际上并没有在我的控制器中编写该代码,它只是从用户的客户端 ID 属性派生而来。
【问题讨论】:
-
Controller.View() 方法受到保护。除非您从控制器派生您的视图渲染,否则您无法访问受保护的方法。
-
@MichaelG 谢谢,但即使我这样做
public static class ViewRenderer : Controller它仍然给出同样的错误。 -
使用派生类时,去掉“Controller.”,使用base.View(view);
标签: c# asp.net-mvc design-patterns asp.net-mvc-5 architecture