gpt4 book ai didi

asp.net-mvc - ASP.NET 使用 LINQ 处理 DB 表单

转载 作者:行者123 更新时间:2023-12-02 03:04:47 26 4
gpt4 key购买 nike

我正在学习 ASP.NET。那么问题来了:

我在数据库中有 2 个表。一个是“客户”,另一个是“比尔”。两者都有一些属性,但重要的是“Bill”有 FK“customer_id”,可以告诉 Bill 属于谁。我有以下用于创建“Bill”的代码,由 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 以及所有其他信息?

最佳答案

由于您不希望用户在这种情况下能够更改客户,因此我建议添加一个新的 CreateForCustomer 操作,其中包含可用于捕获的 customer_id 参数来自列表中链接的 customer_id。然后使用该 id 设置账单的 customer_id 的值。在这里,我假设您的 customer_id 是一个 Guid 但如果它是诸如 intstring 之类的其他内容,那么改成这样。

在你的 Controller 中:

// 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 View 中:

@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 操作方法和 View 添加一堆 if 语句更简单,也更容易混淆。

关于asp.net-mvc - ASP.NET 使用 LINQ 处理 DB 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com