在ASP.NET MVC中,有多種方法可以實現下拉框綁定數據。以下是常用的幾種方法:
控制器代碼:
ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");
視圖代碼:
@Html.DropDownListFor(model => model.CategoryId, ViewBag.Categories as SelectList, "請選擇分類", new { @class = "form-control" })
視圖模型代碼:
public class MyViewModel
{
public int CategoryId { get; set; }
public SelectList Categories { get; set; }
}
控制器代碼:
var model = new MyViewModel
{
Categories = new SelectList(db.Categories, "Id", "Name")
};
return View(model);
視圖代碼:
@Html.DropDownListFor(model => model.CategoryId, Model.Categories, "請選擇分類", new { @class = "form-control" })
控制器代碼:
public ActionResult GetCategories()
{
var categories = db.Categories.ToList();
return Json(categories, JsonRequestBehavior.AllowGet);
}
視圖代碼:
<select id="categoryList" class="form-control"></select>
<script>
$(function() {
$.ajax({
type: 'GET',
url: '/Controller/GetCategories',
success: function(data) {
$.each(data, function(index, category) {
$('#categoryList').append('<option value="' + category.Id + '">' + category.Name + '</option>');
});
}
});
});
</script>
這些方法都可以實現下拉框數據綁定,選擇合適的方法取決于具體的需求和項目結構。