我需要一些帮助来做一些我认为很简单的事情。我正在使用带有 CodeFirst (CTP5) 的 ASP.net MVC 3
我有两个实体:公司和位置。一家公司可以有很多地点。课程如下(去除所有不必要的信息)
public class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
public class Location
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public virtual Company Company { get; set; }
}
现在在我的控制器中,我只允许在公司的上下文中创建位置,因此始终传入公司 ID(在视图中,我在只读字段中显示公司的名称,但不允许用户更改/编辑它。
public ActionResult Create(int companyId)
{
Company company = _session.Single<Company>(c => c.Id == companyId);
Location newLocation = new Location {Company = company};
return View(newLocation);
}
[HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
_session.Add<Location>(location);
_session.CommitChanges();
return RedirectToAction("Index");
} else {
return View(location);
}
}
现在,每当我尝试创建新位置时,ModelState.IsValid 始终为 false,因为未提供 location.Company.Name 并且是 Company 的必填字段。我从不尝试在这里创建一家新公司,我只是尝试创建一个引用正确公司的位置。我不想将 Name 属性添加到视图中只是为了让 ModelState 进行验证。这怎么能轻松完成?我应该传递与视图不同的东西吗?或视图?