Posted By

praveensewak on 05/31/12


Tagged

aspnet MVC DropDownList mvc3


Versions (?)

Dropdown list ASP.NET MVC


 / Published in: C#
 

Dropdown list bound in MVC using Entity Framework

  1. // Model
  2. public partial class Product
  3. {
  4. private Category _category;
  5.  
  6. public Category Category
  7. {
  8. get
  9. {
  10. if (_category == null)
  11. {
  12. var categoryRepository = new CategoryRepository();
  13.  
  14. var cat = categoryRepository.Select(categoryid);
  15.  
  16. _category = cat.First();
  17. }
  18.  
  19. return _category;
  20. }
  21. }
  22. }
  23.  
  24. //Controller
  25.  
  26. public ProductController() : base()
  27. {
  28. var categoryRepo = new CategoryRepository();
  29. ViewData["categories"] = categoryRepo.Select().ToList();
  30. }
  31.  
  32. // View
  33. <% using (Html.BeginForm()) {%>
  34.  
  35. <fieldset>
  36. <legend>Fields</legend>
  37. <p>
  38. <label for="Category">Category:</label>
  39. <%= Html.DropDownList("categoryid", new SelectList((IEnumerable)ViewData["categories"], "id", "name")) %>
  40. <%= Html.ValidationMessage("categoryid", "*") %>
  41. </p>
  42. <p>
  43. <label for="name">Name:</label>
  44. <%= Html.TextBox("name") %>
  45. <%= Html.ValidationMessage("name", "*") %>
  46. </p>
  47. <p>
  48. <input type="submit" value="Create" />
  49. </p>
  50. </fieldset>
  51.  
  52. <% } %>
  53.  
  54. // View
  55. <% using (Html.BeginForm()) {%>
  56.  
  57. <fieldset>
  58. <legend>Fields</legend>
  59. <p>
  60. <label for="id">ID:</label>
  61. <%= Html.Encode(Model.id) %>
  62.  
  63. </p>
  64. <p>
  65. <label for="category">Category:</label>
  66. <%= Html.DropDownList("categoryid", new SelectList((IEnumerable)ViewData["categories"], "id", "name")) %>
  67. <%= Html.ValidationMessage("categoryid", "*") %>
  68. </p>
  69. <p>
  70. <label for="name">Name:</label>
  71. <%= Html.TextBox("name", Model.name) %>
  72. <%= Html.ValidationMessage("name", "*") %>
  73. </p>
  74. <p>
  75. <input type="submit" value="Save" />
  76. </p>
  77. </fieldset>
  78.  
  79. <% } %>

Report this snippet  

You need to login to post a comment.