Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

razor - Where should I place Declarative HTML helpers in ASP.NET MVC 3

I'm trying to make a declarative HTML Helper as specified in ScottGu's Razor post, but I'm not having much luck. I tried putting a Helpers.cshtml file with a DateTimeHelper in Views/Helpers but it wouldn't pick it up, so I tried in App_Code as per the MVC 3 Beta post. Now it picks it up, but when I try to use it in a file like so:

@DateTimeHelper(DateTime.Now)

The compiler complains that DateTimeHelper doesn't exist.

Some weird things: If I rename the file to DateTime.cshtml, I get a different error, something about the particular code in my helper.

For completeness' sake, here's the helper's code:

@helper DateTimeHelper(DateTime t, bool longDate = true, bool showTime = true, bool longTime = true) {
    <time datetime='@t.ToUniversalTime()'>
        @if(longDate) {
            if(showTime) {
                if(longTime) {
                    @t.ToLongDateString() @t.ToLongTimeString();
                } else {
                    @t.ToLongDateString() @t.ToShortTimeString();
                }
            } else {
                @t.ToLongDateString()
            }
        } else {
            if(showTime) {
                if(longTime) {
                    @t.ToShortDateString() @t.ToLongTimeString();
                } else {
                    @t.ToShortDateString() @t.ToShortTimeString();
                }
            } else {
                @t.ToShortDateString()
            }
        }
    </time>
}

The helper is used in a certain view like this:

@model dynamic

<div>
    <p> The current time is @DateTimeHelper(DateTime.Now)</p>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To use the "@helper" feature in Razor you need to place the CSHTML file in the App_Code folder of your app. There is no "Views/Helpers" folder in ASP.NET MVC 3. ScottGu's blog post was written before the feature was fully implemented, and some of the notes there are not entirely accurate anymore.

To call the "@helper" that you wrote you have to include both the filename as well as the name of the helper inside it. For example, if you have this helper:

~/App_Code/MyHelper.cshtml

And this content:

@helper ShowStuff(string stuff) {
    <p>@stuff</p>
}

Then you call it like so:

@MyHelper.ShowStuff("some stuff!")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...