C# 将参数传递给另一个视图

C# Passing params to another view

我有一个公司可以拥有 none 或一个或多个客户的设置。所以客户table和公司table之间没有严格的关系。我创建了一个搜索视图,其中填充了所有公司。然后使用按钮可以将客户附加到公司。我认为使用 ActionLink 我可以实现这一点,所以我的搜索(视图)有

@Html.ActionLink("Book", "Book", new { id = a.CompanyId })

循环模型以获取所有公司列表的位置。现在,当我单击 link 时,它会使用正确的参数填充地址,Companies/Book/1 我正在使用的 ID 是 1。这是正确的,但是我登陆的视图是一个新的客户模型.

public class CustomerModel
{
    [HiddenInput(DisplayValue = true)]
    public long CompanyId { get; set; }

    [HiddenInput(DisplayValue = false)]
    public long CustomerId { get; set; }

    [Display(Name = "Customer Name")]
    [Required(ErrorMessage = "* required")]
    public string CustomerName { get; set; }

    [Display(Name = "Address Line 1")]
    [Required(ErrorMessage = "* required")]
    public string AddressLine1 { get; set; }

    [Display(Name = "Postcode")]
    [Required(ErrorMessage = "* required")]
    public string Postcode { get; set; }

    [Display(Name = "Phone Number")]
    [Required(ErrorMessage = "* required")]
    [RegularExpression(@"\d*", ErrorMessage = "Not a valid phone number")]
    public string PhoneNo { get; set; }
}

即使我能够看到正在传递的 ID(使用 FireBug)是 1,但不知何故,当我单击按钮将视图提交给控制器时,我得到的是 0。为什么会这样?谁能帮帮我?

编辑 - 1

这是控制器。

    public ActionResult Book()
    {
        return View(new CustomerModel());
    }

    [HttpPost]
    public ActionResult SaveCustomer(CustomerModel model)
    {
        _companyService.SaveCustomer(model);
        return RedirectToAction("Index");
    }

我试过使用 CompanyId 而不是 id,它出现了另一个错误。

Before submitting the Form, Address bar has : http://localhost:53294/Companies/Book?CompanyId=1

After submitting the Form, Address Bar has : http://localhost:53294/Companies/SaveCustomer

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Customer_dbo.Company_CompanyId". The conflict occurred in database "BoilerServicing", table "dbo.Company", column 'CompanyId'. The statement has been terminated.

保存方法本身,

    public void SaveCustomer(CustomerModel customer)
    {
        using (var db = new BoilerServicingDbContext())
        {
            Customer entity;
            if (customer.CustomerId > 0)
            {
                entity = db.Customers.First(x => x.Id == customer.CustomerId);
            }
            else
            {
                entity = new Customer();
                db.Customers.Add(entity);
            }

            entity.Name = customer.CustomerName;
            entity.TelephoneNumber = customer.PhoneNo;
            entity.AddressLine1 = customer.AddressLine1;
            entity.PostCode = customer.Postcode;
            entity.CompanyId = customer.CompanyId;

            db.SaveChanges();
        }
    }

好了,试了那么多方法,终于到了这个地步。我更改了控制器上的 Action 方法。

    public ActionResult Book(long id)
    {
        return View(new CustomerModel
        {
            CompanyId = id
        });
    }

这好像是我传入Book视图的CompanyId。花了我一段时间,但我到了那里。感谢您的帮助!