开发者

ASP.NET MVC3 Razor: Is it possible to have C# code blocks without @if or @foreach?

I havent really found a solution seaching t开发者_开发知识库hrough SO.

...and suspect I should really do this in the Model...

but is it possible to have C# code blocks where adhoc code can be added eg:

@int daysLeft = CurrentTenant.TrialExpiryDate.Subtract(DateTimeOffset.Now).Days
@if (daysLeft <= 0) {
{
   <text>
   Trial period completed  
   </text>
}
else
{
   <text>
   You have @daysLeft days left of you trial
   </text>
}


Sure it is:

@{
    var one = 1;
    var two = one + one;
}

Phil Haack has a pretty popular blog post summing up Razor syntax.


You can create functions in razor which is what I believe you are looking for.

Another explanation.


You could also use templated razor delagates. http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx

Something like this should work.

public static class RazorExtensions
{
    public static HelperResult TrialMessage(this int days,
      Func<T, HelperResult> template)
    {
        return new HelperResult(writer =>
        {
            if (days <=0)
                template("Trial period completed").WriteTo(writer);
            else
                template("You have " + days  + " days left of you trial").WriteTo(writer);
        });
    }
}

In the view use:

@int daysLeft = CurrentTenant.TrialExpiryDate.Subtract(DateTimeOffset.Now).Days
@daysLeft.TrialMessage(@<text>@item@</text>)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜