Я хочу привязать данные к выпадающему списку, выбрать один и сохранить его в базе данных.
Я успешно связал данные с выпадающим списком, но выдает ошибку
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DiseaseType'.
при нажатии кнопки сохранения.
Код Edit.cshtml:
<div class="form-group">
@Html.LabelFor(model => model.DiseaseType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.DiseaseType, ViewData["Diseases"] as SelectList, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DiseaseType, "", new { @class = "text-danger" })
</div>
</div>
Код PatientController.cs:
public ActionResult Edit(int id)
{
List<string> disease = new List<string>();
disease.Add("Select");
disease.Add("Cancer");
disease.Add("Heart");
SelectList Diseases = new SelectList(disease);
ViewBag.Diseases = Diseases;
PatientDBHandle pdb = new PatientDBHandle();
return View(pdb.GetPatient().Find(p => p.ID == id));
}
Patient.cs класс:
[Required(ErrorMessage="Please select Disease Type.")]
public string DiseaseType { get; set; }
PatientDBHandle.cs код:
public bool UpdatePatient(Patient patient)
{
connection();
SqlCommand cmd = new SqlCommand("UpdatePatientDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", patient.ID);
cmd.Parameters.AddWithValue("@DiseaseType", patient.DiseaseType);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if(i >= 1)
{
return true;
}
else
{
return false;
}
}
Я создал одну таблицу Patient
CREATE TABLE [dbo].[Patient] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[DiseaseType] VARCHAR (20) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
Я новичок в mvc, пожалуйста, помогите.