你可以嘗試做一些這樣的:
這是一個MvcUtility類我用的時候,我想呈現在Web表單PartialViews或ChildActions頁面,我不認爲我已經在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您將需要共享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; }
}
在你的web表單
最後頁面調用像這樣:
<% MvcUtility.RenderPartial("_SomePartial", null); %>
<% MvcUtility.RenderAction("SomeController", "SomeAction", new { accountID = Request.QueryString["id"], dateTime = DateTime.Now }); %>
這很有點作品,感謝adwise! – Sergio