Get a prevalues dropdownlist in Razor (umbraco) for a datatype

by Damiaan Peeters 15. April 2012 19:38

Sometimes you get tired of reinventing the wheel.  Every time I start typing code using the XpathNodeIterator classes I have that feeling.  Every time I search a few minutes for a better solution, but the only solution is the umbraco.library.GetPrevalues()  . 

So I copied the code from there into a .Net class.    I created it as a Razor extention, and copied the values into a dictionary.

namespace MyRazorStuff {
  public static Dictionary<int, object> GetPrevalues(this RazorLibraryCore library, int dataTypeId) {
    XPathNodeIterator preValueRootElementIterator = umbraco.library.GetPreValues(dataTypeId); 
    preValueRootElementIterator.MoveNext(); //move to first 
    XPathNodeIterator preValueIterator = preValueRootElementIterator.Current.SelectChildren("preValue", ""); 
    var retVal = new Dictionary<int, object>(); 

    while (preValueIterator.MoveNext()) { 
      retVal.Add(Convert.ToInt32(preValueIterator.Current.GetAttribute("id", "")), preValueIterator.Current.Value); 
    } 
    return retVal; 
  } 
}

Why does it mean? After I add a using statement to the RazorScript

@using MyRazorStuff 

I can now make a dropdownbox in a razorscript from the datatype prevalues pretty easily:

@{         
  var myvalues = Library.GetPrevalues(GsTehuurTekoopDataTypeId);
  if (myvalues.Count > 0) {
    <select id="ohyeahbaby">
      @foreach (var item in myvalues) {
        <option value="@item.Key">@item.Value</option>    
      }
    </select>     
  }   
}

How about that?  Please share your thought.  Is it wrong to use a dictionary in favor of a XPathNodeIterator?  Should be using a direct database connection much faster?

Who.I.am

Certified Umbraco, .net and Azure developer, seo lover. Magician in my spare time.

Month List