我有一个公司可以没有或一个或多个客户端的设置。因此,客户表和公司表之间没有严格的关系。我创建了一个搜索视图,在其中填入所有公司。然后使用一个按钮客户可以连接到公司。我想用一个ActionLink
我将能够做到这一点,所以我的搜索(图)有,C#传递参数到另一个视图
@Html.ActionLink("Book", "Book", new { id = a.CompanyId })
在模型环绕在让所有的企业名单。现在,当我点击链接时,它会用正确的参数填充地址,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,它提出了另一个错误。
提交表单,地址栏有:http://localhost:53294/Companies/Book?CompanyId=1
提交表格后,地址栏有:http://localhost:53294/Companies/SaveCustomer
INSERT语句冲突与外键约束“FK_dbo.Customer_dbo。 Company_CompanyId”。数据库“BoilerServicing”中出现冲突,表“dbo.Company”,列“CompanyId”。 该声明已被终止。
的本身保存方法,
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();
}
}
你可以发布你的控制器方法吗? – dotnetom 2015-02-23 18:06:08
同样的问题在这里? #PaulFrancis – 2015-02-23 18:15:20
@dotnetom,我现在已经完成了工作,当我回到家时,会在几分钟内更新这篇文章。我确实尝试过使用companyId,但会再次尝试。 – PaulFrancis 2015-02-23 18:20:44