Credo di aver collegato i miei dati correttamente, ma non riesco a ottenere la proprietà del mio testo per ogni oggetto SelectListItem da mostrare correttamente.Perché sto ricevendo "System.Web.Mvc.SelectListItem" nel mio DropDownList?
Il mio modello:
public class Licenses
{
public SelectList LicenseNames { get; set; }
public string SelectedLicenseName { get; set; }
}
Controller:
[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");
}
}
Vista:
@Html.DropDownList("LicenseNames", new SelectList(Model.LicenseNames, "Value", "Text", Model.LicenseNames.SelectedValue), new { htmlAttributes = new { @class = "form-control focusMe" } })
In aggiunta alla risposta di Shyju, si noti che il 2 ° parametro di 'DropDownList()' è 'IEnumerable'. Lo crei usando 'new SelectListItem {Value = row [" Description "]. ToString(), Text =" test "})' che è tutto ciò di cui hai bisogno. Creando un secondo identico nel controller usando 'new SelectList()' (dove hai dimenticato di impostare le proprietà 'Text' e' Value') e poi creando un terzo identico nella vista è solo un inutile overhead aggiuntivo. –