我正在创建一个Web应用程序,我似乎无法使用外键创建或编辑条目。我正在创建一个下拉列表来编辑记录,并且正在正确填充。但是无论何时我使用该外键编辑或创建新记录,我都会得到“值'2'无效。”
我的控制器
Start
我的观点
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "chimeTimeID,ScheduleID,ChimeTimeStamp")] ChimeTime chimeTime)
{
ViewData["scheduleID"] = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
ViewBag.defaultModem = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
if (ModelState.IsValid)
{
db.Entry(chimeTime).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(chimeTime);
}
我的模特
<div class="form-group">
@Html.LabelFor(model => model.ScheduleID.ScheduleName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="dropdown">
@Html.DropDownListFor(model => model.ScheduleID, (SelectList)ViewBag.ScheduleName, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ScheduleID, "", new { @class = "text-danger" })
</div>
</div>
那么我做错了什么?在我看来,MVC没有将我的结果从表单解析为类似于它的int。
答案 0 :(得分:0)
显然这应该是这样的:
我的控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "chimeTimeID,schedule,ChimeTimeStamp")] ChimeTime chimeTime)
{
ViewData["schedule"] = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
ViewBag.schedule = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
if (ModelState.IsValid)
{
chimeTime.ScheduleID = db.Schedules.Find (Int32.Parse (Request ["schedule"]));
db.ChimeTimes.Add(chimeTime);
db.SaveChanges();
return RedirectToAction("Index");
}
buildChimeJob(chimeTime);
return View(chimeTime);
}
我的观点:
<div class="form-group">
@Html.LabelFor(model => model.schedule, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="dropdown">
@Html.DropDownListFor(model => model.schedule, (SelectList)ViewBag.schedule, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.schedule, "", new { @class = "text-danger" })
</div>
</div>
我的模特:
[Table("P_ChimeTime")]
public class ChimeTime
{
[Key]
public int chimeTimeID { get; set; }
public virtual Schedule ScheduleID { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:T}", ApplyFormatInEditMode = true)]
public DateTime ChimeTimeStamp { get; set; }
[ForiegnKey("ScheduleID")]
public int schedule {get; set;}
}