我正在尝试使用LINQ查询的结果在MVC应用程序中创建下拉列表。我使用this answer作为参考。但是,当我尝试为我的案例实施时,我收到错误:'System.String' does not contain a property with the name 'SAMPLING_EVENT'
我的代码如下:
控制器
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.Title = "Sample Tracker Tool";
DateTime nineMonthsAgo = DateTime.Now.AddDays(-270);
var context = new EDMS_Entities();
var resultSet = (from samplingEvents in context.EDMS_SAMPLES
where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
orderby samplingEvents.SAMPLING_EVENT
select samplingEvents.SAMPLE_ID)
.Distinct();
var viewModel = new SamplingEventsVM();
viewModel.SamplingEvents = new SelectList(resultSet, "SAMPLING_EVENT", "SAMPLING_EVENT");
return View(viewModel);
}
}
ViewModel类
public class SamplingEventsVM
{
public int SelectedSamplingEvent { get; set; }
public SelectList SamplingEvents { get; set; }
}
查看
@model SamplingEventsVM
<h2>@ViewBag.Title</h2>
<span>
@Html.DropDownListFor(model => model.SelectedSamplingEvent, Model.SamplingEvents, "Sampling Event")
</span>
我做错了什么?
答案 0 :(得分:1)
您正在选择此select samplingEvents.SAMPLE_ID
因此,您可能会获得int
的列表,具体取决于您的ID类型
然后,您尝试使用属性值"SAMPLING_EVENT"
在您使用。
填充resultSet的int
对象上不存在
而是这样做:
var resultSet = (from samplingEvents in context.EDMS_SAMPLES
where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
orderby samplingEvents.SAMPLING_EVENT
select samplingEvents)
.Distinct();