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

I really did not find a solution that worked through SO.

... and I suspect that I should really do this in the model ...

but is it possible to have C # code blocks where you can add adhoc code, for example:

@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> } 
+6
source share
3 answers

Of course this is:

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

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

+9
source

You can create functions in a razor that I think you're looking for.

Another explanation .

+4
source

You can also use template delagates razors. 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>) 
+3
source

Source: https://habr.com/ru/post/890620/


All Articles