2011-03-22 2 views
2

HTML의 재사용 가능한 조각을 만들려고합니다. 추가 HTML을 매개 변수의 일종으로 받아 들일 수 있기를 원합니다.동적 내용으로 재사용 가능한 HTML 조각을 만드는 방법

내 재사용 가능한 코드는

<div class="dialog" id="@Model.HtmlId"> 

    <!-- My reusable code needs to go here --> 
</div> 

부분 뷰를 만들기 쉬운,하지만 문제는 부분적인 전망이 매개 변수로 모델을 받아들이는 것이다.

현재 해결책은 추합니다.

@Html.Partial("_startDialog", new { HtmlId="someIdGoesHere" }); 

<form> 
    <!-- Some form elements go here --> 
</form> 

@Html.Partial("_endDialog"); 

<div class="dialog" id="@Model.HtmlId"> 

    <form> 
    <!-- Some form elements go here --> 
    </form> 
</div> 

이 어떻게 줄이를 스트리밍 할 수 있습니다 렌더링합니다.

public class MvcDialog : IDisposable 
{ 
    public MvcDialog(ViewContext context, IDictionary<string, object> htmlAttributes) 
    { 
     this.context = context; 
     this.htmlAttributes = htmlAttributes; 

     Begin(); 
    } 

    private ViewContext context; 
    private IDictionary<string, object> htmlAttributes; 
    private TagBuilder tag; 
    private bool disposed; 

    protected virtual void Begin() 
    { 
     tag = new TagBuilder("div"); 
     tag.MergeAttributes(htmlAttributes); 
     tag.AddCssClass("dialog"); 

     context.Writer.Write(tag.ToString(TagRenderMode.StartTag)); 
    } 

    public virtual void End() 
    { 
     Dispose(true); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (!disposed) 
     { 
      disposed = true; 
      context.Writer.Write(tag.ToString(TagRenderMode.EndTag)); 
     } 
    } 

    public void Dispose() 
    { 
     Dispose(true); 
     GC.SuppressFinalize(this); 
    } 
} 

public static class MvcDialogExtensions 
{ 
    public static MvcDialog Dialog(this HtmlHelper self) 
    { 
     return Dialog(self, new RouteValueDictionary()); 
    } 
    public static MvcDialog Dialog(this HtmlHelper self, object htmlAttributes) 
    { 
     return Dialog(self, new RouteValueDictionary(htmlAttributes)); 
    } 
    public static MvcDialog Dialog(this HtmlHelper self, IDictionary<string, object> htmlAttributes) 
    { 
     return new MvcDialog(self.ViewContext, htmlAttributes); 
    } 
} 

사용법 : 우아함이 트릭해야

답변

3

좋은 :-) 것

@using (Html.Dialog(new { id = "mightyDialog" })) 
{ 
    <text>awesome content</text> 
} 
+0

안녕 루카스, 해당 솔루션은 일반 텍스트 위대한 작품을,하지만 당신은 <

을 시도하는 경우 입력 유형 = '텍스트'>
대신에 , 그때 그것은 작동을 멈춘다 :-(훌륭한 대답. –

+1

당신의 콘텐츠가있을 때 당신은 필요하지 않습니다 '' html 태그가있는 타트. 그러나 그것은 어쨌든 작동해야하며, 정확히 작동하는지 게시 할 수 있습니까? –

관련 문제