Andrew Simpson
Andrew Simpson

Reputation: 7324

DataBinding: 'Models' does not contain a property with the name 'Key'

Relatively new to MVC.

I was using EF as my ORM to my SQL database but I have been told to not use EF and just use a normal data tier instead.

I am getting an error when I am loading a model with a SelectList

This is my 'DAL':

public  SQLiteDataReader GetFilters()
{
    var cmd = new SQLiteCommand();
    cmd.Connection = GetConnection();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "SELECT * FROM Filter";
    return cmd.ExecuteReader();
}

This is my 'biz':

public IEnumerable<Filters> LoadFilterTypes()
{
    var ctx = new DAL();

    List<Filters> filters = new List<Filters>();
    using (var dt = ctx.GetFilters())
    {
        while (dt.Read())
        {
            filters.Add(new Filters { Key = Convert.ToInt16(dt["FilterKey"]), FilterType = dt["FilterType"].ToString() });
        }
    }
    return filters;
}

This is my Model for 'Filters':

public class Filters
{
    public string FilterType;
    public int Key;
}

This is my ViewModel:

public class CloudData
{
    [Display(Name = "SelectedFilter")]
    public int? SelectedFilter { get; set; }
    public SelectList FilterList { get; set; }
}

This is my Controller:

    public IEnumerable<Filters> LoadFilterTypes()
    {
        var ctx = new DAL();

        List<Filters> filters = new List<Filters>();
        using (var dt = ctx.GetFilters())
        {
            while (dt.Read())
            {
                filters.Add(new Filters { Key = Convert.ToInt16(dt["FilterKey"]), FilterType = dt["FilterType"].ToString() });
            }
        }
        return filters;
    }

    public ActionResult Feed(string id, string guid)
    {
        var model = new CloudData();

        var filterList = LoadFilterTypes();
        model.FilterList = new SelectList(filterList, "Key", "FilterType");

        return View(model);
    }

This is my error:

enter image description here

I had put a break-point on the filterlist and it is being populated.

What am I doing wrong please?

thanks

Upvotes: 2

Views: 2238

Answers (1)

Erik Schierboom
Erik Schierboom

Reputation: 16636

I think the problem might be that you declared Key as a field, not as a property. Could you try this:

public class Filters
{
    public string FilterType { get; set; }
    public int Key { get; set; }
}

Upvotes: 6

Related Questions