C# MVC DropDownList using Entity Framework Table Values

The code example below creates a C# MVC DropDownList from database table via the Entity Framework. This article has example code for the Model, View and Controller to make it all work!

This example is based on a list of business unit names that are coming from a database lookup table access via Entity Framework. It is also wired up to persist a selection value using a session value. If session value is present, use it as the Selected item on the list.

This example came from a real project so I’ve had to replace some original code related to Entity and Model name referenced with HARDCODEDVALUES or generic reference like, modelName, you can replace with your own values.

If you are struggling with this as I was for a bit this example might be just what you need to get you over the code hump.

Here are a couple of references that cover the details of the larger overall process of wiring up the Entity Framework for your project that I’m skipping over in the article.

C# MVC DropDownList using Entity Framework

When you get through all the big stuff covered in the links below you still might end up stuck on the little details of implementing the C# MVC drop down list. That is what the intent of this article is.

Model

In the example below we create a public property called BusinessUnitList in our model that the page is using to access the C# controller values.

BusinessUnitList needs to be instantiated as an IEnumerable of type “SelectedListItem” to store our drop down list values.

The IEnumerable exposes an enumerator, which supports a simple iteration over a non-generic collection. In simple terms, IEnumerable, just adds methods and properties like an index value for each item and methods to loop through a list of items. That kind of stuff.

public IEnumerable<SelectListItem> BusinessUnitList {get; internal set;}

View

The version of C# MVC I was using has 7 method overloads for the HTML Helper DropDownList . You’ll find all sorts of examples. Just so you know, there are 7 different ways to do this that work. OMG!

This example is pretty strait forward. This code creates a dropdown list and if you have a session value for this Model. On page load, “Please Select” text will be selected.

@Html.DropDownList("Business Unit", Model.BusinessUnitList, "- - - Please Select - - -")

Controller

This was the hardest part of implementing this code.

In the MVC Controller for this View, we create a list to store the drop down list data.

Next, using Entity Framework, we use a dbContext to connect to an already defined Entity to get the data from the BusinessUnit lookup table.

We dump the data in a tempList variable. For reference, the lookup table name replaces the ENTITYMODELNAMEGOESHERE place holder value.

tempList is modeled after the Entity Framework model for the BusinessUnit lookup table in the database.

Next, we need to convert tempList from the BusinessUnit lookup table model in to a list C# MVC can use for the drop down list that is of type SelectListItem that represents the selected item in an instance of the SelectList class.

We set the default value of the drop down list in case of user posted back by storing that value in a session and referencing here in the code, Selected = (m.BusinessRefId == modelName.BusinessUnit).

//Create List of Business Units for the Drop Down List
IEnumerable<SelectItemListItem> businessUnitList = new List<SelectListItem>();
using (ENTITYNAMEHERE = dbContext = new ENTITYNAMEHERE())
    {
        List<ENTITYMODELNAMEGOESHERE> tempList = dbContext.ENTITYMODELNAMEGOESHERE.OrderBy(p => p.Name).ToList();

busniessUnitList = tempList.Select(m => new SelectListItem { Text = m.Name, Value = m.BusinessRefId, Selected = (m.BusinessRefId == modelName.BusinessUnit) });
        modelName.BusinessUnitList = businessUnitList;
    } 

modelName.BusinessUnitList = businessUnitList;

Windows USB WMI Scripting using VBScript

I’m looking to release one more Windows WMI Script for getting USB information from a Windows PC.

I don’t recall where I first got this script or what specific problem I was trying to solve but this Window WMI VBScript loops through all the USB devices on a PC.

I’ve modified this script a bit to look for something called “SymbolicName” and fire off a message when that value is found. This was something I must have been troubleshooting with respect to USB devices working or not and if drivers are properly installed.

WMI VBScript

' Get the serial number of a usb device

'USB_REGKEY sets the regkey where displays are found. Don't change except for debugging
'I only change it when I am looking at a .REG file that someone sent me saying that the
'code doesn't work.
Const USB_REGKEY="HKLM\SYSTEM\CurrentControlSet\Enum\USB\"
Const USB_REGKEY2="SYSTEM\CurrentControlSet\Enum\USB\"

Const DEBUGFILE="NUL"
'if set to 1 then output debug info to DEBUGFILE (also writes debug to screen if running under cscript.exe)
Const DEBUGMODE=0

'simple function to provide a wmi registry provider
'to all the other registry functions (regenumkeys, reggetstringvalue, etc...)
Function GetWMIRegProvider()
	strComputer = "."
	Set GetWMIRegProvider=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
End Function

'if debugmode=1 the writes dubug info to the specified
'file and if running under cscript also writes it to screen.
Sub DebugOut(strDebugInfo)
	if DEBUGMODE=0 then
		exit sub
	end if

	strCurrScriptHost=lcase(right(wscript.fullname,len(wscript.fullname)-len(wscript.path)-1))
	
	if strCurrScriptHost="cscript.exe" then 
		wscript.echo "Debug: " & strDebugInfo
		AppendFileMode=8
		set objDebugFSO=CreateObject("Scripting.FileSystemObject")
		set objDebugStream=objDebugFSO.OpenTextFile(DEBUGFILE,AppendFileMode,True,False)
		objDebugStream.writeline strDebugInfo
		objDebugStream.Close
		set objDebugStream=Nothing
		set objDebugFSO=Nothing
	end if
End Sub 

'function to parse the specified hive
'from the registry functions above
'to all the other registry functions (regenumkeys, reggetstringvalue, etc...)
Function SetHive(RegKey)
	HKEY_CLASSES_ROOT=&H80000000
	HKEY_CURRENT_USER=&H80000001
	HKEY_CURRENT_CONFIG=&H80000005
	HKEY_LOCAL_MACHINE=&H80000002
	HKEY_USERS=&H80000003
	strHive=left(RegKey,instr(RegKey,"\"))
	if strHive="HKCR\" or strHive="HKR\" then
		SetHive=HKEY_CLASSES_ROOT
	end if
	if strHive="HKCU\" then
		SetHive=HKEY_CURRENT_USER
	end if
	if strHive="HKCC\" then
		SetHive=HKEY_CURRENT_CONFIG
	end if
	if strHive="HKLM\" then
		SetHive=HKEY_LOCAL_MACHINE
	end if
	if strHive="HKU\" then
		SetHive=HKEY_USERS
	end if
End Function


'simple function to provide an
'easier interface to the wmi registry functions
Function RegEnumKeys(RegKey)
	hive=SetHive(RegKey)
	set objReg=GetWMIRegProvider()
	strKeyPath = right(RegKey,len(RegKey)-instr(RegKey,"\"))
	objReg.EnumKey Hive, strKeyPath, arrSubKeys
	RegEnumKeys=arrSubKeys
End Function

'This function returns an array of all subkeys of the 
'regkey defined by DISPLAY_REGKEY
'(typically this should be "HKLM\SYSTEM\CurrentControlSet\Enum\USB")
Function GetAllUSBDevicesInReg()
	dim arrResult()
	redim arrResult(0)
	dim arrResult2()
	redim arrResult2(0)	
	dim arrResult3()
	redim arrResult3(0)		
	intArrResultIndex=-1
	intArrResultIndex2=-1
	intArrResultIndex3=-1
	
	arrtmpkeys=RegEnumKeys(USB_REGKEY)
	
	
	if vartype(arrtmpkeys)<>8204 then
		arrResult(0)="{ERROR}"
		GetAllUSBDevicesInReg=false
		debugout "Display=Can't enum subkeys of display regkey"
	else
		for tmpctr=0 to ubound(arrtmpkeys)
			arrtmpkeys2 = RegEnumKeys(USB_REGKEY& arrtmpkeys(tmpctr))
			
			for tmpctr2 = 0 to ubound(arrtmpkeys2)
				arrtmpkeys3 = RegEnumKeys(USB_REGKEY& arrtmpkeys(tmpctr) & "\" & arrtmpkeys2(tmpctr2))
				intArrResultIndex=intArrResultIndex+1
				redim preserve arrResult(intArrResultIndex)
				arrResult(intArrResultIndex)=USB_REGKEY & arrtmpkeys(tmpctr) & "\" & arrtmpkeys2(tmpctr2)
				debugout "USB=" & arrResult(intArrResultIndex)
				'WScript.Echo "From #1 USB=" & arrResult(intArrResultIndex)
				
				for tmpctr3 = 0 to ubound(arrtmpkeys3)
					intArrResultIndex2=intArrResultIndex2+1
					redim preserve arrResult2(intArrResultIndex2)
					arrResult2(intArrResultIndex2)=USB_REGKEY & arrtmpkeys(tmpctr) & "\" & arrtmpkeys2(tmpctr2) & "\" & arrtmpkeys3(tmpctr3)
					debugout "USB=" & arrResult2(intArrResultIndex2)
					'WScript.Echo "From #2 USB=" & arrResult2(intArrResultIndex2)
					if InStr(arrResult2(intArrResultIndex2),"Device Parameters") > 0 then
						WScript.Echo arrResult2(intArrResultIndex2)
						'WScript.Echo arrtmpkeys(tmpctr) & "\" & arrtmpkeys2(tmpctr2) & "\" & arrtmpkeys3(tmpctr3)
						GetRegValues(arrtmpkeys(tmpctr) & "\" & arrtmpkeys2(tmpctr2) & "\" & arrtmpkeys3(tmpctr3))
					end if
								
					'for tmpctr4 = 0 to ubound(arrtmpkeys4)
					'	intArrResultIndex3=intArrResultIndex3+1
					'	redim preserve arrResult3(intArrResultIndex3)
					'	arrResult2(intArrResultIndex2)=USB_REGKEY & arrtmpkeys(tmpctr) & "\" & arrtmpkeys2(tmpctr2) & "\" & arrtmpkeys3(tmpctr3)
					'	debugout "USB=" & arrResult2(intArrResultIndex2)
					'	WScript.Echo "From #2 USB=" & arrResult2(intArrResultIndex2)
					'next				
				next
			next 
		next
	end if
	GetAllUSBDevicesInReg=arrResult
End Function



' Constants (taken from WinReg.h)
'
Sub GetRegValues(strKeyPath)
const HKLM = &H80000002

dim keyPath
keyPath = "SYSTEM\CurrentControlSet\Enum\USB\" & strKeyPath

dim reg

dim valueNames, types
dim value
dim i

  set reg = getObject( "Winmgmts:root\default:StdRegProv" )

  if reg.enumValues( HKLM, keyPath, valueNames, types ) = 0 then
    if isArray( valueNames ) then
      for i = 0 to UBound( valueNames )
        reg.getStringValue HKLM, keyPath, valueNames(i), value
		If InStr(ValueNames(i),"SymbolicName") > 0 then
			msgBox("I found you! " & valueNames(i) & "=" & value )
		end if
      next
    end if
  end if

End Sub



GetAllUSBDevicesInReg

Here is a screenshot of the code on line 160. If we see a value that has the text “SymbolicName”, the script will stop and display that value in a message box.