i am using code first method , i need to bind a dropdown using repositry , viewmodel
i have a viewmodel Infoviewmodel where i need to populate the dropdown from tblstates as per country selected
i have created a Repository DropDownList Repository on Repository folder
DropDownList.cs has the below code
public List<SelectListItem> GetstateList(int countryId)
{
var statelist = (from p in db.state
where (p.stateId == stateId)
select new SelectListItem
{
Text = p.state,
Value = p.stateID.ToString()
});
return statelist.ToList();
}
viewmodel
public class infoviewmodel
{
[Key]
public int stateID { get; set; }
public string stateName { get; set; }
public virtual state state{get;set;}
public string ddlstate
{
get;
set;
}
//DropDownList Values
public List<SelectListItem> StateValue
{
get;
set;
}
}
controller
//Creating an instance of infoviewmodel
infoviewmodel objinfoviewmodel = new infoviewmodel();
objinfoviewmodel.StateValue = objRepository.GetstateList(1);
return View(objinfoviewmodel);
}
state model
public class state
{
public int stateID { get; set; }
[StringLength(50, ErrorMessage = "state name cannot be greater than 50 characters.")]
[Display(Name = "state Name")]
public string stateName { get; set; }
public int? countryId { get; set; }
//[ForeignKey("countryId")]
public virtual Country Country { get; set; }
}
i am not able to create view using the viewmodel
error
There was an error running the selected code generator: 'Unable to retrieve metadata for 'Application1.ViewModels.infoviewmodel'. One or more validation errors were detected during model generation:
SelectListItem: : EntityType 'SelectListItem' has no key defined. Define the key for this EntityType. SelectListItems: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
is the above method a correct way ? or is there any best method