development

Razor 선언적 뷰에서 MVC HtmlHelper 확장 사용

big-blog 2020. 7. 12. 09:00
반응형

Razor 선언적 뷰에서 MVC HtmlHelper 확장 사용


MVC 3 RTM 프로젝트의 App_Code 폴더에 Razor 선언 도우미를 만들려고했습니다.

내가 겪었던 문제는 ActionLink와 같은 MVC HtmlHelper 확장을 사용할 수 없다는 것입니다. 컴파일 된 도우미는에서 파생되고 속성이 아닌 유형을 System.Web.WebPages.HelperPage노출 하기 때문 입니다.HtmlSystem.Web.WebPages.HtmlHelperSystem.Web.Mvc.HtmlHelper

내가 겪고있는 오류의 예는 다음과 같습니다.

'System.Web.Mvc.HtmlHelper'에 'ActionLink'에 대한 정의가 포함되어 있지 않으며 'System.Web.Mvc.HtmlHelper'유형의 첫 번째 인수를 허용하는 확장 메소드 'ActionLink'를 찾을 수 없습니다 (사용 지시문이 누락 되었습니까? 또는 조립 참조?)

내 유일한 해결책은 내 자신의 HelperPage를 만들고 Html 속성을 재정의하는 것입니다.

using System.Web.WebPages;

public class HelperPage : System.Web.WebPages.HelperPage 
{
    // Workaround - exposes the MVC HtmlHelper instead of the normal helper
    public static new HtmlHelper Html
    {
        get { return ((System.Web.Mvc.WebViewPage) WebPageContext.Current.Page).Html; }
    }
}

그런 다음 모든 도우미의 맨 위에 다음을 작성해야합니다.

@inherits FunnelWeb.Web.App_Code.HelperPage
@using System.Web.Mvc
@using System.Web.Mvc.Html

@helper DoSomething()
{
    @Html.ActionLink("Index", "Home")
}

MVC 3에서 이것이 어려울 것입니까, 아니면 뭔가 잘못하고 있습니까?


이 질문에 대한 Marcind의 답변살펴보십시오 . 당신이 겪고있는 것은 App_Code폴더 에 선언적 뷰를 넣는 것의 한계입니다 .

헬퍼를 App_Code에 배치하는 것은 작동하지만 특정 MVC 시나리오에 영향을 미치는 특정 제한이 있습니다 (예 : 표준 MVC HTML 헬퍼에 대한 액세스 권한 없음)


페이지 도우미에 액세스 할 수 있도록 WebPages 도우미에 대한 확장 메서드를 만들었습니다.

public static HtmlHelper GetPageHelper(this System.Web.WebPages.Html.HtmlHelper html)
{
 return ((System.Web.Mvc.WebViewPage) WebPageContext.Current.Page).Html;
}

Omar는 여기에 정답을 얻었지만 무언가를 추가하고 싶었습니다 (Omar의 답변을 답변으로 자유롭게 표시하십시오).

우리는 v1에서 이것을 알고 제품에서 큰 수정을 할 수 없었지만 David Ebbo (ASP.Net 팀의 설계자)는 기본적으로 첫 번째 탐색 인 Visual Studio Code Generator 샘플을 게시했습니다. 우리 가이 작업을 올바르게 수행하기 위해 찾고있는 아이디어의 종류 : http://blogs.msdn.com/b/davidebb/archive/2010/10/27/turn-your-razor-helpers-into-reusable-libraries .aspx

그것을 시도하고 당신의 생각을 참조하십시오! 자신의 블로그에 게시하여 의견이 있으면 David에게 알려주십시오.


@Jakes 답변과 유사합니다.

public static class MvcIntrinsics {
    public static System.Web.Mvc.HtmlHelper Html {
        get { return ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html; }
    }

    public static System.Web.Mvc.AjaxHelper Ajax {
        get { return ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Ajax; }
    }

    public static System.Web.Mvc.UrlHelper Url {
        get { return ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Url; }
    }

}

용법:

@MvcIntrinsics.Html.Raw("test")

출처 : Dino Esposito-Microsoft ASP.NET MVC 프로그래밍


대안 솔루션 :

이것을 면도기 도우미 파일 위에 추가하십시오.

@functions {
    public static System.Web.Mvc.HtmlHelper<object> HHtml = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
}

다음과 같이 호출하십시오.

@HHtml.ActionLink("actionname")

For the benefit of searchers, I got the same error when creating MVC views as part of a class library (for component re-use). The solution, partially alluded to above, was to add the following using statements at the top of the .cshtml file:

@using System.Web.Mvc
@using System.Web.Mvc.Html

No further work necessary.


My approach to this is to simply pass the page as a parameter to the helper method. So in your example it would be:

@helper DoSomething(WebViewPage page)
{
    @page.Html.ActionLink("Index", "Home")
}

Then in your Razor view where you need it call it like this:

@YourHelperFilename.DoSomething(this)

Doing this immediately gives you access to page properties like Html or Url that you usually have (and through that the HtmlHelper extensions).

As an additional benefit (if you require this), you also get access to instance properties such as the page's ViewData.


I know that there are some intellisense issues with MVC 3. I think the helpers will still work if you have the namespace set in web.config.

MVC 3 RTM has just been realeased are you using this or a beta?


Looks like the ASP.NET MVC has fixed this issue in VS 2013. See this post http://aspnet.uservoice.com/forums/41201-asp-net-mvc/suggestions/3670180-support-helper-extensionmethod-this-htmlhelper-ht

참고URL : https://stackoverflow.com/questions/4710853/using-mvc-htmlhelper-extensions-from-razor-declarative-views

반응형