[英]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.