Reputation: 23004
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
Upvotes: 0
Views: 441
Reputation: 1039438
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.
Upvotes: 7