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