Asp.net mvc ASP.NET使用LINQ处理DB窗体

Asp.net mvc ASP.NET使用LINQ处理DB窗体,asp.net-mvc,linq,Asp.net Mvc,Linq,我正在学习ASP.NET。问题是: 我有两张DB格式的表。一个是“客户”,另一个是“账单”。两者都有一些属性,但重要的是“Bill”有FK“customer_id”,它告诉我们账单属于谁。我有以下代码创建“法案”,由ASP.NET生成 // GET: Bills/Create public ActionResult Create(int? id) { ViewBag.customer_id = new SelectList(db.Custo

我正在学习ASP.NET。问题是:

我有两张DB格式的表。一个是“客户”,另一个是“账单”。两者都有一些属性,但重要的是“Bill”有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,我有下拉菜单来选择一个现有客户,这很好

在客户列表中,我想按每个客户的姓名设置一个链接,该链接使我能够创建与前一个相同的账单表单,但没有下拉菜单,相反,客户id应该通过链接发送,我通过此代码成功地获得了该链接

@Html.ActionLink("Add bill", "Create", "Bills", new { id = item.id_customer }, null)

问题是,我如何在数据库中将该ID与所有其他信息一起使用?

既然您不希望用户能够更改客户,在这种情况下,我建议添加一个新的
CreateForCustomer
操作,该操作带有
customer\u ID
参数,您可以使用该参数从列表上的链接中捕获客户ID。然后使用该id设置账单客户id的值。在这里,我假设您的
客户id
Guid
,但如果它是
int
字符串
之类的值,则将其更改为该值

在控制器中:

// 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能做什么,这个解决方案似乎比在现有的创建操作方法和视图中添加一堆
if
语句更简单,也更容易理解。

首先,谢谢你编辑我的帖子,谢谢你的回答。我在我的帖子中犯了错误,现在我编辑了它,我已经添加了参数来创建GET操作,但我复制了旧的。所以基本上,我所要做的就是在下拉列表中使用ID作为默认值,我将它添加为您,但它不会做任何更改(好的,杰里米,再次谢谢,我明白了,我所要做的就是“隐藏”下拉列表?对吗?:)但是如何隐藏它呢?若我在表单文件中删除它,那个么我会得到错误。你们有两个选择。隐藏下拉列表是其中之一,尽管通常这不是最好的做法,而是使用元素。我会更新答案,告诉你在你的情况下我会怎么做。老兄,再一次,谢谢你。我删除了旧的控制器,做了新的,做了像你们一样的动作,它在我的测试控制器中工作,现在我试着把它放在原来的控制器中,希望它能工作。再一次,泰:)你帮了我很多:)