Adr*_*ore 48 c# asp.net-mvc html-helper razor asp.net-mvc-3
我正在尝试编写一个简单的声明性html帮助器:
@helper Echo(string input) {
@input
}
Run Code Online (Sandbox Code Playgroud)
如果我将它嵌入我想要使用它的页面,帮助程序工作正常.但是如果我将它移动到一个单独的.cshtml
文件并将该文件放在~/Views/Helpers
目录中,我的视图就不能再编译了,因为找不到帮助器.根据Scott Gu 关于Razor的博客文章,它应该有效.
我究竟做错了什么?
mar*_*ind 49
~/Views/Helpers
ScottGu帖子中描述的位置在MVC 3 RTM中不起作用.在撰写这篇文章的时候,这是一个我们正在折腾的设计理念,但最终我们无法实现它.
将您的助手放在App_Code中有效,但是有一些限制会影响某些MVC场景(例如:无法访问标准MVC Html.
助手)
Ser*_*-Tm 36
简单的解决方法:
在每个帮助器中添加参数WebViewPage页面.
App_Code文件\ Test.cshtml:
@using System.Web.Mvc.Html
@using System.Web.Mvc
@helper HelloWorld(WebViewPage page)
{
@page.Html.Label("HelloWorld")
}
Run Code Online (Sandbox Code Playgroud)
在任何页面中使用此帮助程序:
@Test.HelloWorld(this)
Run Code Online (Sandbox Code Playgroud)
正如marcind所说,~/Views/Helpers
由于我们的编译模型存在一些限制,我们无法支持该位置.
我们正在为声明性HTML帮助程序开发一个更好的解决方案,但它不会生成v1.对于v1,我们有两个解决方案:
在App_Code中,@ helper需要它才能正常工作:
// These are important for `Html.RouteLink` and such.
@using System.Web.Mvc;
@using System.Web.Mvc.Routing;
@using System.Web.Mvc.Html;
@using System.Web.Mvc.Razor;
@helper SomeHelper()
{
// Get page and pull helper references from it.
var wvp = PageContext.Page as System.Web.Mvc.WebViewPage;
var Url = wvp.Url; // UrlHelper access
var Html = wvp.Html; // HtmlHelper access
var ViewBag = wvp.ViewBag;
// Helper code comes here...
}
Run Code Online (Sandbox Code Playgroud)
我也按照Scott博客中列出的步骤操作,但也无法使其正常工作.
我做了一些搜索,发现了这个链接:http://dotnetslackers.com/articles/aspnet/Experience-ASP-NET-MVC-3-Beta-the-Razor-View-Engine.aspx#s19-create-custom-helper -方法
按照步骤进行操作.密钥似乎既是App_Code文件夹,也是调用帮助程序时使用文件名点帮助程序名称.
归档时间: |
|
查看次数: |
37046 次 |
最近记录: |