您可以尝试执行以下操作:
这是我想在 Web 表单页面中呈现 PartialViews 或 ChildActions 时使用的 MvcUtility 类,但是我认为我没有在 UserControl 中使用它。
不确定您使用的是哪个 MVC 版本,但我知道这适用于 MVC 3 和 Razor Views。
public static class MvcUtility
{
public static void RenderPartial(string partialViewName, object model)
{
// Get the HttpContext
HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);
// Build the route data, pointing to the Some controller
RouteData routeData = new RouteData();
routeData.Values.Add("controller", typeof(Controller).Name);
// Create the controller context
ControllerContext controllerContext = new ControllerContext(new RequestContext(httpContextBase, routeData), new Controller());
// Find the partial view
IView view = FindPartialView(controllerContext, partialViewName);
// create the view context and pass in the model
ViewContext viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), httpContextBase.Response.Output);
// finally, render the view
view.Render(viewContext, httpContextBase.Response.Output);
}
private static IView FindPartialView(ControllerContext controllerContext, string partialViewName)
{
// try to find the partial view
ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName);
if (result.View != null)
{
return result.View;
}
// wasn't found - construct error message
StringBuilder locationsText = new StringBuilder();
foreach (string location in result.SearchedLocations)
{
locationsText.AppendLine();
locationsText.Append(location);
}
throw new InvalidOperationException(String.Format("Partial view {0} not found. Locations Searched: {1}", partialViewName, locationsText));
}
public static void RenderAction(string controllerName, string actionName, object routeValues)
{
RenderPartial("RenderActionUtil", new RenderActionVM() { ControllerName = controllerName, ActionName = actionName, RouteValues = routeValues });
}
}
要呈现 ChildAction,您将需要 Shared MVC Views 文件夹中的局部视图:
@model YourNamespace.RenderActionVM
@{
Html.RenderAction(Model.ActionName, Model.ControllerName, Model.RouteValues);
}
和视图模型:
public class RenderActionVM
{
public string ControllerName { get; set; }
public string ActionName { get; set; }
public object RouteValues { get; set; }
}
最后在您的网络表单页面调用中,如下所示:
<% MvcUtility.RenderPartial("_SomePartial", null); %>
<% MvcUtility.RenderAction("SomeController", "SomeAction", new { accountID = Request.QueryString["id"], dateTime = DateTime.Now }); %>