2010-05-24 9 views
4

이 같은 다른 HTML을 래핑하는 Asp.Net MVC에서 도우미를 만들 수있는 방법은 용기가 있습니까 :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 문자열을 반환합니다." 기본적으로 도우미 메서드는 호출 될 때 Response.Write 열기 태그를 사용하고 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

+0

이것을보고 나면 올바르지 않습니다. 이렇게하면 내용이 페이지 상단에 쓰여집니다. helper.ViewContext.Writer.Write (...) 여야합니다. 또한 WrapThis는 정적 클래스에 있어야하며 MyContainer 메서드에는 HttpResponseBase가 아닌 HtmlHelper가 인수로 있어야합니다. – LarryBud

관련 문제