Reputation: 5670
My code is like this
namespace DiagnosisApp.Models
{
public class ProcedurePrice
{
public int ID { get; set; }
public int DepartmentID { get; set; }
public int ProcedureID { get; set; }
public int InsuranceProviderID { get; set; }
public int ProcedureCategoryID { get; set; }
public int ProcedureSubCategoryID { get; set; }
[ForeignKey("ID")]
public virtual Department Department { get; set; }
[ForeignKey("ID")]
public virtual InsuranceProvider InsuranceProvider { get; set; }
[ForeignKey("ID")]
public virtual ProcedureCategory ProcedureCategory { get; set; }
[ForeignKey("ID")]
public virtual ProcedureSubCategory ProcedureSubCategory { get; set; }
}
}
Controller
public ActionResult Create()
{
ViewBag.DepartmentID = new SelectList(db.Departments, "ID", "Name");
ViewBag.ProcedureSubCategoryID = new SelectList(db.ProcedureSubCategories, "ID", "Name");
return View();
}
And in my view
@Html.DropDownList("ProcedureID", null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ProcedureID)
Everything looks okay to me, But it throws an error
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'ProcedureID'.
Can anyone point out what I am doing wrong here?
Upvotes: 3
Views: 31186
Reputation: 62488
The mistake is you are putting it in ViewBag.ProcedureSubCategoryID
while you are passing ProcedureID
int Html.DropDownList()
and also you are passing SelectList
parameter null
. A quick fix is to just replace ProcedureSubCategoryID
with ProcedureID
in Html.DropDownList()
as key in first parameter:
you have three ways to resolve this.
Instead of passing null
in second parameter which accepts of type SelectList
you can do something like this:
@Html.DropDownList("ProcedureID", ViewBag.ProcedureSubCategoryID as SelectList, new { @class="form-data" })
public ActionResult Create()
{
ViewBag.DepartmentID = new SelectList(db.Departments, "ID", "Name");
ViewBag.ProcedureSubCategoryID = new SelectList(db.ProcedureSubCategories, "ID", "Name");
return View();
}
@Html.DropDownList("ProcedureSubCategoryID", null, new { @class = "form-control" })
or alternative is to store it in ProcedureID
in your action:
public ActionResult Create()
{
ViewBag.DepartmentID = new SelectList(db.Departments, "ID", "Name");
ViewBag.ProcedureID = new SelectList(db.ProcedureSubCategories, "ID", "Name");
return View();
}
and in View:
@Html.DropDownList("ProcedureID", null, new { @class = "form-control" })
Upvotes: 7
Reputation: 2560
I suppose you're missing something like
ViewBag.ProcedureID = new SelectList(db.ProcedureCategory, "ID", "Name");
I think you have to inizialize ViewBag.ProcedureId
Upvotes: 2