/ Published in: C#
Dropdown list bound in MVC using Entity Framework
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Model public partial class Product { private Category _category; public Category Category { get { if (_category == null) { var cat = categoryRepository.Select(categoryid); _category = cat.First(); } return _category; } } } //Controller public ProductController() : base() { ViewData["categories"] = categoryRepo.Select().ToList(); } // View <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="Category">Category:</label> <%= Html.DropDownList("categoryid", new SelectList((IEnumerable)ViewData["categories"], "id", "name")) %> <%= Html.ValidationMessage("categoryid", "*") %> </p> <p> <label for="name">Name:</label> <%= Html.TextBox("name") %> <%= Html.ValidationMessage("name", "*") %> </p> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> // View <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="id">ID:</label> <%= Html.Encode(Model.id) %> </p> <p> <label for="category">Category:</label> <%= Html.DropDownList("categoryid", new SelectList((IEnumerable)ViewData["categories"], "id", "name")) %> <%= Html.ValidationMessage("categoryid", "*") %> </p> <p> <label for="name">Name:</label> <%= Html.TextBox("name", Model.name) %> <%= Html.ValidationMessage("name", "*") %> </p> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %>