Tôi tin rằng tôi đã ràng buộc dữ liệu của mình một cách chính xác, nhưng dường như tôi không thể nhận được thuộc tính văn bản của mình cho mỗi SelectListItem để hiển thị chính xác.Tại sao tôi nhận được "System.Web.Mvc.SelectListItem" trong DropDownList của tôi?
mô hình của tôi:
public class Licenses
{
public SelectList LicenseNames { get; set; }
public string SelectedLicenseName { get; set; }
}
Bộ điều khiển:
[HttpGet]
public ActionResult License()
{
try
{
DataTable LicsTable = BW.SQLServer.Table("GetLicenses", ConfigurationManager.ConnectionStrings["ProfressionalActivitiesConnection"].ToString());
ProfessionalActivities.Models.Licenses model = new ProfessionalActivities.Models.Licenses();
model.LicenseNames = new SelectList(LicsTable.AsEnumerable().Select(row =>
new SelectListItem
{
Value = row["Description"].ToString(),
Text = "test"
}));
return PartialView("_AddLicense", model);
}
catch (Exception ex)
{
var t = ex;
return PartialView("_AddLicense");
}
}
Xem:
@Html.DropDownList("LicenseNames", new SelectList(Model.LicenseNames, "Value", "Text", Model.LicenseNames.SelectedValue), new { htmlAttributes = new { @class = "form-control focusMe" } })
Ngoài câu trả lời của Shyju, lưu ý rằng tham số thứ 2 của 'DropDownList()' là 'IEnumerable'. Bạn tạo ra nó bằng cách sử dụng 'new SelectListItem {Value = row [" Description "]. ToString(), Text =" test "})' đó là tất cả những gì bạn cần. Tạo một cái giống hệt nhau thứ hai trong bộ điều khiển bằng cách sử dụng 'new SelectList()' (nơi bạn quên đặt thuộc tính 'Text' và' Value') và sau đó tạo ra một cái giống hệt thứ 3 trong khung nhìn chỉ là vô nghĩa. –