0

Before I start, I know this NOT considered good practice, but was wondering how (if at all) it would be possible to define a method inside my view.

Im using C# in ASP.Net MVC

The following does not seem to work:

decimal DoCalculation(IEnumerable<MyItems> items){
    ...
}

N.B. I AM NOT USING THE RAZOR VIEW ENGINE

Jimbo
  • 22,379
  • 42
  • 117
  • 159
  • Possible duplicate of [How do I define a method in Razor?](http://stackoverflow.com/questions/5159877/how-do-i-define-a-method-in-razor) – Yannick Blondeau Feb 05 '13 at 13:27
  • 1
    You should really put this code inside your model. This is swimming against the MVC current. – Jon Feb 05 '13 at 13:27
  • http://blogs.msdn.com/b/timlee/archive/2010/07/30/using-functions-in-an-asp-net-page-with-razor-syntax.aspx – ken2k Feb 05 '13 at 13:29

1 Answers1

6

If you are using the Razor view engine you could declare inline functions:

@functions {
    public string DoCalculation(IEnumerable<MyItems> items) {
        ...    
    }
}

or also you could use inline helpers:

@helper DoCalculationAndOutputResult(IEnumerable<MyItems> items)
{
    foreach (var item in items)
    {
        <div>@item.SomeValue</div>
    }
}

And if you are using the WebForms view engine:

<script type="text/C#" runat="server">
    public string DoCalculation(IEnumerable<MyItems> items) {
        ...    
    }
</script>

Obviously writing C# code in views is as bad as not writing any code at all. Worth mentioning for other people reading this so that they do not do the same mistake as you.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928