In a nutshell, I would like to simplify some of my MVC pages by creating a stati开发者_C百科c class to get the data from a data store of some sort then return one of multiple views based on some internal flags.
internal static class StaticPageContent
{
internal static ViewModels.Display GetPage(string Map = null, int? ID = null) {...}
internal static ActionResult ReturnView(ViewModels.CMS.Display vm) {...}
}
Then, in any of my controller actions I could call it something like:
public ActionResult ActionName()
{
var vm = StaticPageContent.GetPage("/Home");
return StaticPageContent.ReturnView(vm);
}
Where the ReturnView() method would return one of multiple (shared) views:
internal static ActionResult ReturnView(ViewModels.CMS.Display vm)
{
if (vm.useLoremIpsum)
return View("LoremIpsum", vm);
else
{
if (vm.canEdit)
return View("ViewReadWrite", vm);
else
return View("ViewReadOnly", vm);
}
}
What is the right way of returning a View(...) object from a non-Controller class? The above will not compile as the View(...) is part of the Controller class.
NOTE: I believe I got something like this working but the demands on my time sent me in another direction. I am hoping to be able to open this project back up to see what I did and post it here. Stay tuned!
Simply put, the right way is to not do it in a static class. (IMO, of course). Especially if you're getting "data from a data store" - this should not be static.
In my opinion, create a protected method in a base controller, or use child actions and render them out using Html.Action
.
Just instantiate one, though I don't think I would recommend this.
http://msdn.microsoft.com/en-us/library/system.web.mvc.viewresult.aspx
var result = new ViewResult(){
ViewName = "ViewReadWrite"
}
result.ViewData.Model = vm; // ViewData may need to be instantiated first.
return result;
精彩评论