2010-05-24 9 views
4

有沒有一種方法,使在Asp.Net MVC幫手包裝其他HTML這樣的:Asp.Net MVC的自定義控件 - 集裝箱

<div class="lightGreyBar_left"> 
    <div class="lightGreyBar_right"> 

     <!--Content--> 
     <h3> 
      Profiles</h3> 
     <div class="divOption"> 
      <%= Html.ActionLinkWithImage("Create new", "add.png", Keys.Actions.CreateProfile, "add")%> 
     </div> 
     <!--Content--> 

    </div> 
</div> 

讓助手將呈現包含傳遞給的div和內容輔助方法作爲參數。

回答

4

看看窗體幫助器的方法。它們提供的語法是這樣的:

<% using (Html.BeginForm()) { %> 
    <p>Form contents go here.</p> 
<% } %> 

執行這種HTML輔助的模式比平常稍微有點複雜「只返回一個HTML字符串」類型的幫手。基本上,當它被調用時,你的幫助器方法將會打開標記,並返回一些實現了IDisposable的自定義對象。當處理返回值時,它應該結束標記Response.Write

這裏是一個工作示例:

public static MyContainer WrapThis(this HtmlHelper html) 
{ 
    html.ViewContext.HttpContext.Response.Write("<div><div>"); 
    return new MyContainer(html.ViewContext.HttpContext.Response); 
} 

public class MyContainer : IDisposable 
{ 
    readonly HttpResponseBase _httpResponse; 
    bool _disposed; 

    public MyContainer(HttpResponseBase httpResponse) 
    { 
     _httpResponse = httpResponse; 
    } 

    public void Dispose() 
    { 
     if (!_disposed) 
     { 
      _disposed = true; 
      _httpResponse.Write("</div></div>"); 
     } 

     GC.SuppressFinalize(this); 
    } 
} 

這將允許您將視圖改寫爲這樣的:

<% using (Html.WrapThis()) { %> 
    <h3>Profiles</h3> 
    <div class="divOption"> 
     <%= Html.ActionLinkWithImage("Create new", "add.png", Keys.Actions.CreateProfile, "add")%> 
    </div> 
<% } %> 
+0

「WrapThis」需要在一個靜態類..這不是很明顯在這個例子中。 – LarryBud 2017-05-19 18:42:40

+0

看完後這是不正確的。這樣做會將內容寫入頁面的頂部。它應該是helper.ViewContext.Writer.Write(...)。此外,WrapThis需要處於靜態類中,而MyContainer方法應該將HtmlHelper作爲參數,而不是HttpResponseBase。 – LarryBud 2017-05-19 18:55:07