Saturday 6 June 2015

Define a c-sharp function in razor cshtml page

Function inside .cshtml page

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}

<h2>index</h2>
@GetSomeString()

Helper inside .cshtml page

@helper WelcomeMessage(string username)
{
    <p>Welcome, @username.</p>
}
Then you invoke it like this:
@WelcomeMessage("some username")
If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    Func<int,int,int> Sum = (a, b) => a + b;
}

<h2>Index</h2>

@Sum(3,4)