[英]Using asp.net mvc view in asp.net control
以下代码将一个asp.net Web窗体控件添加到Web窗体应用程序中的内容占位符:
var someControl = (System.Web.UI.UserControl)LoadControl("~/serverPath/" + ControlName + ".ascx");
phContentControls.Controls.Add(someControl);
所以我想知道有什么方法可以将呈现的asp.net mvc视图添加到控件中吗?
天哪,wtf我刚刚问过:D
您可以尝试执行以下操作:
这是我想在Webforms页面中呈现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; }
}
最后在您的Webforms页面调用中,如下所示:
<% MvcUtility.RenderPartial("_SomePartial", null); %>
<% MvcUtility.RenderAction("SomeController", "SomeAction", new { accountID = Request.QueryString["id"], dateTime = DateTime.Now }); %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.