So i'm new to Razor and i'm trying to figure out how to access stuff inside a @functions block in a .cshtml file in the App_Code folder. Here is what I am trying to do:
I have a simple .cshtml file in the macroScripts folder wich contains this code:
@{
var someIntLikeString = 200;
var someNode = @Model.NodeById(toint(someIntLikeString, 1049));
<h1>@someNode.Name</h1>
}
As you kan se I use a "toint" method, this method i have placed in another file that I've placed in the App_Code folder. Here is the Path: App_Code/myhelpers.cshtml, it contains the following code:
@functions{
int toint(string s, int defaultValue)
{
if (!string.IsNullOrWhiteSpace(s)) return int.Parse(s);
return defaultValue;
}
}
So my question is how I would go about accessing the "toint" method in my myhelpers.cshtml. I've tried this:
var someNode = @Model.NodeById(@myhelpers.toint(someIntLikeString, 1049));
Your toint method would probably be safer if it was something like this:
int toint(string s, int defaultValue) { int value; if (!int.TryParse(s, out value)) value = defaultValue; return value; }
That way it will always return your default value if the string cannot be parsed to an int. In your implementation there is always a risk that if a non-empty string (such as "xxx") is passed in you would end up with a FormatException.
Accessing functions in App_Code folder
So i'm new to Razor and i'm trying to figure out how to access stuff inside a @functions block in a .cshtml file in the App_Code folder. Here is what I am trying to do:
I have a simple .cshtml file in the macroScripts folder wich contains this code:
As you kan se I use a "toint" method, this method i have placed in another file that I've placed in the App_Code folder. Here is the Path: App_Code/myhelpers.cshtml, it contains the following code:
So my question is how I would go about accessing the "toint" method in my myhelpers.cshtml.
I've tried this:
But does'nt work.
Any help would be much appreciated
/Thor
Thor,
Use
and you're good to go.
Cheers,
/Dirk
Sweet! Now it works like a charm. Thanks a million :D
/Thor
Thor,
Your toint method would probably be safer if it was something like this:
That way it will always return your default value if the string cannot be parsed to an int. In your implementation there is always a risk that if a non-empty string (such as "xxx") is passed in you would end up with a FormatException.
Hi Dan,
Thanks for the pointer! Was'nt aware of that:-)
#h5yr
/Thor
is working on a reply...