Mình có đọc được 1 bài của bạn trên web cách Binding (truyền dữ liệu) vào DropDownList trong MVC Asp.net toàn tập với trọn bộ truyền dữ liệu, binding khá chi tiết như sau:
Chuẩn bị:
- Tạo 1 Controller Category có tên : CategoryController trong thư mục Controllers và 1 Model của Controller này có tên CategoryViewModel trong thư mục Models.
CategoryController.cs
Mã: public class CategoryController : Controller
{
// GET: Category
public ActionResult Index()
{
var model = new CategoryViewModel();
// using Model
model.CategoryList = new SelectList(GetAllCategories(), "Id", "Name");
// using ViewBag
ViewBag.VbCategoryList = new SelectList(GetAllCategories(), "Id", "Name");
return View(model);
}
public List<CategoryViewModel> GetAllCategories()
{
var categories = new List<CategoryViewModel>
{
new CategoryViewModel {Id = 1, Name = "Code HTML MVC"},
new CategoryViewModel {Id = 2, Name = "Code ASP.NET MVC"},
new CategoryViewModel {Id = 3, Name = "Code PHP"},
new CategoryViewModel {Id = 4, Name = "Code Java"}
new CategoryViewModel {Id = 5, Name = "Code Ajax"}
};
return categories.ToList();
}
}
CategoryViewModel.cs
Mã: public class CategoryViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public SelectList CategoryList { get; set; }
} Binding (Lấy dữ liệu vào DropDownList)
Cách 1: Binding truyền dữ liệu vào DropDownList bằng cách sử dụng Model
Mã: @Html.DropDownList("ddl1", Model.CategoryList, "--- Select ---") Cách 2: Binding truyền dữ liệu vào DropDownListFor bằng cách sử dụng Model
Mã: @Html.DropDownListFor(m => m.Id, new SelectList(Model.CategoryList, "Value", "Text"), "--- Select ---") Cách 3: Binding truyền dữ liệu vào DropDownList bằng cách sử dụng ViewBag
Mã: @Html.DropDownList("ddl2", ViewBag.VbCategoryList as SelectList, "--- Select ---") Cách 4: Binding truyền dữ liệu vào DropDownList bằng cách sử dụng ViewBag Căn Bản
Mã: <select name="Category">
@foreach (var item in ViewBag.VbCategoryList) {
<option value="@item.Id">@item.Name</option>
}
</select>
Cách 5: Binding truyền dữ liệu vào DropDownList bằng cách sử dụng Harcode
Mã: @Html.DropDownList("ddl3", new List<SelectListItem>
{
new SelectListItem {Text = "Code HTML MVC", Value = "1"},
new SelectListItem {Text = "Code ASP.NET MVC", Value = "2"},
new SelectListItem {Text = "Code PHP", Value = "3"},
new SelectListItem {Text = "Code Java", Value = "4"},
new SelectListItem {Text = "Code Ajax", Value = "5"}
}, "--- Select ---")
|