티스토리 뷰

.NET MVC 패턴, 웹폼에서 부분뷰(Partial View) 사용하기



닷넷 프레임워크 개발 중 .Net Webform 의 Layout.Master 와 .NET MVC에 Header를 같이 넣고 싶은 케이스가 생겼다.

사이트 내부에 웹폼과 MVC 패턴이 모두 존재하기 떄문에, 이에 따라 매번 같은 코드를 수정해야하는 단점 때문에

고민이 많던 찰나에 웹폼 내부에 파샬뷰를 심을 수 있다면, 완화되지 않을까 라는 생각에서 시작해서 한번 도전해 보았다.


먼저 웹폼에서 파샬뷰를 사용할 수 있도록 클래스를 생성해야 한다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
/// <summary>
/// HelperWebFormMVCUtil의 요약 설명입니다.
/// </summary>
public class WebFormController : Controller {}
 
public static class HelperWebFormMVCUtil
{
 
    public static void RenderPartial( string partialName, object model )
    {
        //get a wrapper for the legacy WebForm context
        var httpCtx = new HttpContextWrapper( System.Web.HttpContext.Current );
 
        //create a mock route that points to the empty controller
        var rt = new RouteData();
        rt.Values.Add( "controller""WebFormController" );
 
        //create a controller context for the route and http context
        var ctx = new ControllerContext( 
            new RequestContext( httpCtx, rt ), new WebFormController() );
 
        //find the partial view using the viewengine
        var view = ViewEngines.Engines.FindPartialView( ctx, partialName).View;
 
        //create a view context and assign the model
        var vctx = new ViewContext( ctx, view, 
            new ViewDataDictionary { Model = model },
            new TempDataDictionary(), httpCtx.Response.Output);
 
        //render the partial view
        view.Render( vctx, System.Web.HttpContext.Current.Response.Output );
    }
 
}



기존 razor 에서 파샬뷰 이용시에 분명 이런식으로 사용되어 왔을것이다.(뷰 이름이  _Headerpage.cshtml 의 경우)

@Html.Partial("_Headerpage")


웹폼에서 이용시 다음과 같이 사용하면 된다.

<% HelperWebFormMVCUtil.RenderPartial("_Headerpage"null); %>    







댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함