我想将数据绑定到下拉列表,选择一个并将其保存到数据库中。 我已成功将数据绑定到dropdownlist,但是它给出了错误
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;
}
}
我已经创建了一张病人表
CREATE TABLE [dbo].[Patient] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[DiseaseType] VARCHAR (20) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
我是mvc的新手,请帮助。
答案 0 :(得分:0)
代替在控制器中使用List<string>
和SelectList
,而使用List<SelectListItem>
并将其加载到ViewBag
中:
List<SelectListItem> disease = new List<SelectListItem>();
disease.Add(new SelectListItem { Value = "Select", Text = "Select" });
disease.Add(new SelectListItem { Value = "Cancer", Text = "Cancer" });
disease.Add(new SelectListItem { Value = "Heart", Text = "Heart" });
ViewBag.Diseases = disease;
在您的视图(Edit.cshtml)中,使用ViewBag
进行下拉,如下所示:
@Html.DropDownList("DiseaseType", (IEnumerable<SelectListItem>)ViewBag.Diseases, new { htmlAttributes = new { @class = "form-control" } })
在这里,我将“ DiseaseType”放入模型中,而不是在模型中,但这只是为了说明当您随后发布选择时,为了将该值传递回控制器,请使用名为DiseaseType的字符串(改用模型) ):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TestStack(string DiseaseType)
{
string result = DiseaseType;
return RedirectToAction("Index");
}