0

I'm trying to use the results of a LINQ query to create a dropdownlist in an MVC app. I'm using this answer as a reference. However, when I try to implement for my case I get the error: 'System.String' does not contain a property with the name 'SAMPLING_EVENT'

My code is as follows:

Controller

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 class

public class SamplingEventsVM
{
    public int SelectedSamplingEvent { get; set; }
    public SelectList SamplingEvents { get; set; }
}

View

@model SamplingEventsVM

<h2>@ViewBag.Title</h2>

<span>
    @Html.DropDownListFor(model => model.SelectedSamplingEvent, Model.SamplingEvents, "Sampling Event")
</span>

What am I doing wrong?

Community
  • 1
  • 1
Chris V.
  • 1,123
  • 5
  • 22
  • 50

1 Answers1

1

You are selecting this select samplingEvents.SAMPLE_ID

So you get a List of int maybe, depends on your ID type

Then you try to make a select list with the property value "SAMPLING_EVENT"

Which doesn't exist on the int object you filled resultSet with.

Instead do this:

    var resultSet = (from samplingEvents in context.EDMS_SAMPLES
                    where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
                    orderby samplingEvents.SAMPLING_EVENT
                    select samplingEvents)
                    .Distinct();
TheNorthWes
  • 2,661
  • 19
  • 35