使用MVC 5。 我正在尝试获取几种视图中的任何一种,我将通过ajax将其注入到Div中。 我正在使用在SO上找到的类,该类将我限制在我从中调用方法的控制器上。
我需要能够为该方法提供我想要的任何类。 有什么办法可行吗?。
这就是我所拥有的。
public static string RenderView(this Controller controller, string viewName, object model)
{
return RenderView(controller, viewName, new ViewDataDictionary(model));
}
public static string RenderView<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
{
var controllerContext = controller.ControllerContext;
controllerContext.Controller.ViewData.Model = model;
//viewName = "List";
//var viewResult = partial ? ViewEngines.Engines.FindPartialView(controllerContext, viewName) : ViewEngines.Engines.FindView(controllerContext, viewName, null);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);
var viewContext = new ViewContext(controllerContext, viewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
从控制器UserAndPersonController
中,我调用此方法,然后尝试获取返回ajax调用所需的任何View并将其放置在特定的Div中。
public string GetView(string viewName, string request)
{
Object obj = new Object();
// Get the various Designations a Person can have
if (request.Contains("User"))
{
obj = new { PersonUserModel = "Catalyst.Mvc.Models.PersonUserModel" };
}
else if (request.Contains("Driver"))
{
obj = new { DriverViewModel = "Models.DriverViewModel" };
}
else if (request.Contains("Debtor"))
{
obj = new { DebtorViewModel = "Models.DebtorViewModel" };
}
// ?? How do I get any Controller context , each must match the respective models
string viewHTML = this.RenderView( "List", obj);
return viewHTML;
}
我也从viewResult.view.render(viewContext,stringWriter);中得到一个错误。线,无论我尝试通过哪个模型。
System.InvalidOperationException:'传递到字典中的模型项的类型为'<> f__AnonymousType14`1 [System.String]',但是此字典需要类型为'Catalyst.Mvc.Models.PersonUserModel'的模型项。 '