2013-10-04 22 views
0

呈現局部視圖我使用ASP.NET MVC 4在這樣的觀點有一個準備好的網址:如何使用URL

var sectoionUrl = Url.Action("DisplayArticleSection", new { id = sectionId }); 

是否有任何助手來解析的方法,用sectionUrl的局部視圖,而不是通過助手再次創造它:

@Html.Action("DisplayArticleSection", new { id = sectionId }) 

事情是這樣的僞代碼:

@Html.RenderUrl(sectionUrl) 

回答

0

定製的HtmlHelper:

public static class RenderUrlHelper 
{ 
    public static void RenderUrl(this HtmlHelper helper, string originUrl) 
    { 
     var originRequest = helper.ViewContext.RequestContext.HttpContext.Request; 

     if (!Uri.IsWellFormedUriString(originUrl, UriKind.Absolute)) 
     { 
      originUrl = new Uri(originRequest.Url, originUrl).AbsoluteUri; 
     } 

     int queryIdx = originUrl.IndexOf('?'); 
     string queryString = null; 
     string url = originUrl; 

     if (queryIdx != -1) 
     { 
      url = originUrl.Substring(0, queryIdx); 
      queryString = originUrl.Substring(queryIdx + 1); 
     } 

     // Extract the data and render the action.  
     var request = new HttpRequest(null, url, queryString); 
     var response = new HttpResponse(new StringWriter()); 
     var httpContext = new HttpContext(request, response); 
     var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); 
     var values = routeData.Values; 
     string controllerName = values["controller"] as string; 
     string actionName = values["action"] as string; 
     var valuesCollection = HttpUtility.ParseQueryString(queryString); 
     RouteValueDictionary routeValues = new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k])); 
     helper.RenderAction(actionName, controllerName, routeValues); 
    } 
} 

一些代碼來測試定製的HtmlHelper:

的TestController:

public class TestController : Controller 
{ 
    public ActionResult Index(string title, int number) 
    { 
     TestModel model = new TestModel { Title = title, Number = number }; 
     return PartialView(model); 
    } 
} 

指數的TestController觀點:

@model TestModel 

<h1>Title: @Model.Title</h1> 
<h2>Number: @Model.Number</h2> 

TestModel:

public class TestModel 
{ 
    public string Title { get; set; } 
    public int Number { get; set; } 
} 

使用在任何視圖:

@{ 
    var actionUrl = Url.Action("Index", "Test", new { number = 123, title = "Hello Url Renderer" }); 
    Html.RenderUrl(actionUrl); 
} 
-1

您可以使用下面的HTML代碼來呈現partail視圖使用

@Html.RenderPartial("NameOfPartialView") 
@Html.Partial("NameOfPartialView") 

OR

您可以創建自定義HTML助手創建功能,例如,

@Html.RenderUrl(sectionUrl) 

以下URL逐步顯示如何創建自定義HTML助手。

Create Custom HTML Helper

+0

我需要從動作獲得局部視圖,而不是直接渲染。我希望有一個內置的幫手。由於沒有人,我會嘗試創建自定義幫手。 – Sergey