Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Thor Madsen-Holm 82 posts 212 karma points c-trib
    Jun 23, 2011 @ 18:54
    Thor Madsen-Holm
    0

    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:

    @{
        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));

    But does'nt work. 

    Any help would be much appreciated

     

    /Thor

  • Dirk De Grave 4541 posts 6021 karma points MVP 3x admin c-trib
    Jun 23, 2011 @ 21:13
    Dirk De Grave
    1

    Thor,

    Use

    @functions{  
        public static
    int toint(string s,int defaultValue)
       
    {
           
    if(!string.IsNullOrWhiteSpace(s))returnint.Parse(s);
           
    return defaultValue;
       
    }  
    }

    and you're good to go.

     

    Cheers,

    /Dirk

     

  • Thor Madsen-Holm 82 posts 212 karma points c-trib
    Jun 24, 2011 @ 07:50
    Thor Madsen-Holm
    0

    Sweet! Now it works like a charm. Thanks a million :D

    /Thor

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Jun 24, 2011 @ 10:23
    Dan Diplo
    0

    Thor,

    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.

  • Thor Madsen-Holm 82 posts 212 karma points c-trib
    Jun 25, 2011 @ 08:54
    Thor Madsen-Holm
    0

    Hi Dan, 

    Thanks for the pointer! Was'nt aware of that:-)

    #h5yr 

    /Thor

Please Sign in or register to post replies

Write your reply to:

Draft