我正在 ASP.NET。所以问题来了:
我在数据库中有 2 张表。一个是"客户",另一个是"账单"。两者都有一些属性,但重要的是"比尔"有FK"customer_id",告诉比尔属于谁。我有以下代码用于创建由 ASP.NET 生成的"账单"。
// GET: Bills/Create
public ActionResult Create(int? id)
{
ViewBag.customer_id = new SelectList(db.Customers, "id_customer", "name");
return View();
}
// POST: racuns/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id_bill,dv_bill,status,dv_paid,customer_id")] bill bill)
{
if (ModelState.IsValid)
{
db.bills.Add(bill);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.customer_id = new SelectList(db.customers, "id_customer", "name", bill.customer_id);
return View(bill);
}
这样,我就有了包含要履行的字段的表单,对于 FK customer_id,我有下拉菜单来选择一个现有客户,这工作正常。
在客户列表中,我想按每个客户名称放置一个链接,该链接将带我创建与上一个相同的账单表单,但没有下拉菜单,而不是该菜单,customer_id应该通过链接发送,我设法通过此代码获得它。
@Html.ActionLink("Add bill", "Create", "Bills", new { id = item.id_customer }, null)
问题是,如何在数据库中将该 ID 与所有其他信息一起使用?
由于您不希望用户在这种情况下能够更改客户,因此我建议添加一个带有customer_id
参数的新CreateForCustomer
操作,您可以使用该操作从列表中的链接捕获customer_id。然后使用该 id 设置账单customer_id的值。在这里,我假设您的customer_id
是Guid
但是如果它是其他东西,例如int
或string
则将其更改为该。
在控制器中:
// GET: Bills/CreateForCustomer
public ActionResult CreateForCustomer(Guid customer_id)
{
// TODO: Verify that customer_id is valid and return HttpNotFound() if not.
return View(new Bill { customer_id = customer_id });
}
// POST Bills/CreateForCustomer
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateForCustomer([Bind(Include = "id_bill,dv_bill,status,dv_paid,customer_id")] bill bill)
{
// TODO: The usual POST stuff like validating and saving the entity.
}
在 CreateForCustomer.cshtml 视图中:
@Html.HiddenFor(model => model.customer_id)
// Instead of:
//@Html.DropDownList("customer_id")
在您的客户列表中,您可以生成如下链接:
// Note that I changed `id` to `customer_id` since that is what the CreateForCustomer action expects
@Html.ActionLink("Add bill", "CreateForCustomer", "Bills", new { customer_id = item.id_customer }, null)
有多种方法可以实现您所追求的目标。我只是想让你了解 MVC 可以做什么,这个解决方案似乎比在现有的 Create 操作方法和视图中添加一堆 if
语句更简单、更少混乱。