[英]how can i call a tolist () method in actionresult of controller
[英]How can I Call Controller and View by string as result for ActionResult?
我正在尝试动态地调用控制器和它的视图,我正在从数据库中检索控制器名称和视图名称,然后我想将其作为Page / Index url的视图结果执行。
基本上我正在尝试做这样的事情:
public class PageController : Controller
{
public ActionResult Index()
{
var controllerName = // logic to get Controller name (already have)
var ViewName = // logic to get View name (already have)
Return View(ControllerName, ViewName); // I want to achieve this functionality without redirect
}
}
我已经尝试过Server.TransferRequest
但是这会导致HttpContext.Items
被清除,我不希望它发生,我也不想重定向,还有其他方法吗?
因此,假设您希望返回基于字符串的操作结果。 你可以使用反射来做到这一点。 所以有些东西:
public ActionResult Index()
{
var controllerName = // logic to get Controller name (already have)
var viewName = // logic to get View name (already have)
//get the current assembly
Type t = typeof(PageController);
Assembly assemFromType = t.Assembly;
//get the controller type from the assembly
Type controllerType = assemFromType.GetType("Namespece." + controllerName);
//get the action method info
MethodInfo actionMethodInfo = controllerType.GetMethods(viewName);
//create an instance of the controller
object controllerInstance = Activator.CreateInstance(controllerType, null);
//invoke the action on the controller instance
return (ActionResult)actionMethodInfo.Invoke(controllerInstance, null);
}
这是未经测试的TBH 我不建议这样做 。 它远没有效果......这里也有一个假设,你的行动不需要可能或可能不是真的参数。 另一种选择(几乎肯定是更好的选择)是使用其他人讨论的Redirect
。
使用此MVC仍然可能在查找视图时遇到问题。 您可能还需要在要调用的操作中对视图路径进行硬编码。 基本上你想要的是非常有问题的,我提到我不建议这样做
这很简单......但我想到你想要这样的东西的其他原因..
public class PageController
{
public ActionResult Index()
{
//Let
var controllerName = "Common"// logic to get Controller name (already have)
var ViewName = "Index" // logic to get View name (already have)
return RedirectToAction("Index", "Common", new { id = "1" });
}
}
在控制器中
public class CommonController : Controller
{
// Initialize with Default value
public ActionResult Index(String id = "0")
{
//Call from PageController
if (id == "1")
{
//Do some stuff
}
//Do other stuff of CommonController
return View();
}
}
我敢打赌你正在寻找RedirectToAction("ActionName", "ControllerName");
我使用下面的方法来获取视图的字符串版本。 也许您可以修改它以根据您的控制器和视图返回视图。 返回IView的部分。
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
我找到了一个解决方案: https : //stackoverflow.com/a/24475934/5485841
你可以返回一个内部有Html.RenderAction
的虚拟视图。 您可以通过ViewBag或Model传递控制器名称和视图名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.