Dotnet 3.5 interview questions and answers Headline Animator

Wednesday, September 9, 2009

How to use drop down list

HTML Helper for DropDownList field will be rendered as select elements in HTML. Check the below code.
  1. <!--HTML helper method for DropDownList field with ID and OptionLabel -->  
  2.  <%= Html.DropDownList("ddlStates") %>  
  3.  <%= Html.DropDownList("ddlStates","Please select state") %>   
  Note : You cannot use these two helper method in HTML unless the datasource/data for binding is assigned/sent from the controller action method.
Exception : There is no ViewData item with the key 'ddlStates' of type 'IEnumerable<SelectListItem>'. 
Code

  1.       <!--HTML helper method for DropDownList field with ID and SelectListItem ( Made "Maryland" to be the default selected value) -->  
  2.            <%= Html.DropDownList("ddlStates",new List <SelectListItem>(){  
  3. new SelectListItem(){ Text="Maryland"Value="MD"Selected=true },    
  4. new SelectListItem(){Text="Kansas"Value="KS"},   
  5. new SelectListItem(){Text="Texas"Value="TX"}}) %> 
  6.  <select id="ddlStates" name="ddlStates"><option selected="selected" value="MD">Maryland</option>   
  7. <option value="KS">Kansas</option>   
  8. <option value="TX">Texas</option>   
  9. </select>  
  10.    <!--HTML helper method for DropDownList field with ID , SelectListItem and OptionLabel(Please select state). OptionLabel will be selected by default if not selected is given in the SelectListItem-->  
  11. <%= Html.DropDownList("ddlStates", new List <SelectListItem>(){  
  12. new SelectListItem(){ Text="Maryland"Value="MD"},    
  13. new SelectListItem(){Text="Kansas"Value="KS"},   
  14. new SelectListItem(){Text="Texas"Value="TX"}},"Please select state") %>  
  15.   <select id="ddlStates" name="ddlStates"><option value="">Please select state</option>   
  16. <option value="MD">Maryland</option>   
  17. <option value="KS">Kansas</option>   
  18. <option value="TX">Texas</option>   
  19. </select>   
  20.  <!--HTML helper method for DropDownList field with ID , SelectListItem , OptionLabel(Please select state) and custom attributes. use '@' if the attribute name is keyword in C# or VB. The default selection will be "Maryland".-->  
  21. <%= Html.DropDownList("ddlStates", new List<SelectListItem>(){  
  22. new SelectListItem(){ Text="Maryland"Value="MD"Selected=true },    
  23. new SelectListItem(){Text="Kansas"Value="KS"},   
  24. new SelectListItem(){Text="Texas"Value="TX"}}, "Please select state", new { @class="error"client_selector="alphanumeric"})%>  
  25.   <select class="error" client_selector="alphanumeric" id="ddlStates" name="ddlStates"><option value="">Please select state</option>   
  26. <option selected="selected" value="MD">Maryland</option>   
  27. <option value="KS">Kansas</option>   
  28. <option value="TX">Texas</option>   
  29. </select> 


No comments:

Post a Comment