Sometimes it's useful to use methods in Razor views. I mean not @helper methods that write out some markup, but methods that return any type you want.
Here's an example of controller, action, and corresponded Razor view template:
Views/Home/Index.cshtml:
As you see, we can use @functions syntax to define areas with methods, that we can use many times for some plain UI-purposes. I say "plain UI-purposes ", because we must remember that Views are bad place to put significant logic into.
Here's an example of controller, action, and corresponded Razor view template:
public class HomeController: Controller
{
public ActionResult Index()
{
return View();
}
}
Views/Home/Index.cshtml:
<html>
<body>
@functions {
public int DoSomethingAndReturnResult(int someValue)
{
var result= someValue*2;
return result;
}
}
@{
var computedValue1 = DoSomethingAndReturnResult(2);
var computedValue2 = DoSomethingAndReturnResult(5);
<div >
@(computedValue1+computedValue2)
</div >
}
</body>
</html>
As you see, we can use @functions syntax to define areas with methods, that we can use many times for some plain UI-purposes. I say "plain UI-purposes ", because we must remember that Views are bad place to put significant logic into.
No comments:
Post a Comment