代码不会将值保存到Musician实体。 我正在使用保存SelectList的ViewBag并显示数据库中的内容,但在保存时,对于调试时的musician.PrimaryInstrument字段,它为null。 剃刀:
lazy var currentArticle: Article = {
let article = Article()
//any other initialization you need
return article
}()
控制器:
<td>
@Html.LabelFor(model => model.PrimaryInstrument, htmlAttributes: new { @class = "control-label col-md-2" })
</td>
<td>
@Html.DropDownList("InstrumentList")
</td>
仪器型号:
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Musician musician = (Musician)db.Contractor.Find(id);
if (musician == null)
{
return HttpNotFound();
}
ViewBag.InstrumentList = new SelectList(db.Instrument, "ID", "Name");
return View(musician);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Musician musician, HttpPostedFileBase image)
{
if(ModelState.IsValid)
{
if (image != null)
{
UploadImage(musician, image);
}
musician.YearsOfExperience = Convert.ToInt16(Request["yearsOfExperience"]);
musician.CreateDate = DateTime.Now;
musician.NextDateAvailable = DateTime.Now;
db.Entry(musician).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Profile");
}
return View();
}
}
音乐家模特:
public class Instrument
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Musician> Musician { get; set; }
}
答案 0 :(得分:1)
您当前未将所选工具绑定到属性PrimaryInstrument
。你的助手应该是
@Html.DropDownListFor(m => m.PrimaryInstrument, (SelectList)ViewBag.InstrumentList)
请注意,这会将ID
的{{1}}属性绑定到属性Instrument
另请注意,如果PrimaryInstrument
无效,您还需要在致电ModelState
之前重新分配ViewBag.InstrumentList
媒体资源ViewBag.InstrumentList = new SelectList(db.Instrument, "ID", "Name");