我在 Controller 中有这个 GET 方法:
public ActionResult Reserve(int id)
{
ViewBag.staffID = new SelectList(context.Staffs, "staffID", "fName");
ViewBag.roomID = id;
return View();
}
对应 View :
@model _00002165.Models.Reservation
@{
ViewBag.Title = "Reserve";
}
<h2>Reserve</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="editor-label">
<label>Room Number</label>
</div>
<div class="editor-field">
<input type="text" value="@ViewBag.roomID" readonly name="roomID"/>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.fromDate)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.fromDate)
@Html.ValidationMessageFor(model => model.fromDate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.toDate)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.toDate)
@Html.ValidationMessageFor(model => model.toDate)
</div>
<div class="editor-label">
<label>Staff:</label>
</div>
<div class="editor-field">
@Html.DropDownList("staffID", "Select Staff")
@Html.ValidationMessageFor(model => model.staffID)
</div>
<button type="submit">Reserve</button>
}
我想使用这些 POST 方法保存来自这些输入的数据:
[HttpPost]
public ActionResult Reserve(Reservation res)
{
if (ModelState.IsValid)
{
var customer = context.Customers.First(x => x.username == User.Identity.Name);
res.customerID = customer.customerID;
context.Reservation.Add(res);
context.Entry(res).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
}
这给我以下错误:
Store update, insert, or delete statement affected an unexpected number of rows (0).
人们建议我将 @Html.HiddenFor(model => model.reservationID)
添加到我的 View 中。
但是 model.reservationID
是空的。
我该如何解决这个问题? 请帮忙
最佳答案
您不应该将数据传输对象传递到您的 View 或从您的 View 传出。使用将返回所需 DTO 的 ToModel 方法创建 View 模型。添加到上下文中,您不需要更改状态。
使用这个
context.Reservation.Add(res);
context.SaveChanges();
删除
context.Entry(res).State = EntityState.Modified;
如果您正在尝试更新,请从数据库中提取记录,进行更改并调用 SaveChanges
关于c# - 无法将对象添加到 context.DbSet。保存更改不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29929778/