我是MVC的新手并且还在学习我的方法,我正在尝试填写下拉列表。我有以下代码(型号):
public class SchoolCodes
{
public int escuelaCode { get; set; }
public string escuelaName { get; set; }
}
public class AllSchoolCodes
{
public List<SchoolCodes> GetSchools()
{
List<SchoolCodes> Codes = new List<SchoolCodes>();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MCE"].ConnectionString);
SqlCommand comm = new SqlCommand("SELECT EscuelaCode, EscuelaName from Escuelas", conn);
conn.Open();
using (var dataReader = comm.ExecuteReader())
{
while (dataReader.Read())
{
SchoolCodes ur = new SchoolCodes();
ur.escuelaCode = Convert.ToInt32(dataReader["EscuelaCode"]);
ur.escuelaName = Convert.ToString(dataReader["EscuelaName"]);
Codes.Add(ur);
}
}
return Codes;
}
}
public class GetSchoolCodeViewModel
{
[Display(Name = "Escuela: ")]
public int SelectedEscuelaCode { get; set; }
public IEnumerable<SelectListItem> AllSchoolCodes { get; set; }
}
控制器:
private IEnumerable<SelectListItem> GetCode()
{
var dbSchoolCodes = new AllSchoolCodes();
var code = dbSchoolCodes
.GetSchools()
.Select(x =>
new SelectListItem
{
Value = x.escuelaCode.ToString(),
Text = x.escuelaName
});
return new SelectList(code, "Value", "Text");
}
public ActionResult Index()
{
var model = new GetSchoolCodeViewModel
{
AllSchoolCodes = GetCode()
};
return View(model);
// return View();
}
现在,我在索引控制器中收到以下错误:错误1无法隐式转换类型&#39; System.Collections.Generic.IEnumerable&#39;到&#39; System.Collections.Generic.IEnumerable&#39;。存在显式转换(您是否错过了演员?)。我被困在这里,完全不知道该怎么做。任何帮助都会很棒。
答案 0 :(得分:1)
Ypu不需要再次创建SelectList
,因为您正在重新调动IEnumerable<SelectListItem>
,您只需以这种方式返回SelectList
:
private SelectList GetCode()
{
var dbSchoolCodes = new AllSchoolCodes();
var code = dbSchoolCodes.GetSchools();
return new SelectList(code, "escuelaCode", "escuelaName");
}
或者如果您想要返回IEnumerable<SelectListItem>
,那么您可以这样做,无需再次创建SelectList
:
private IEnumerable<SelectListItem> GetCode()
{
var dbSchoolCodes = new AllSchoolCodes();
var code = dbSchoolCodes
.GetSchools()
.Select(x =>
new SelectListItem
{
Value = x.escuelaCode.ToString(),
Text = x.escuelaName
});
return code;
}