我尝试添加使用弹出内部PartialView的对象。这是一个简单的租赁应用程序,其数据模型生成模型First至Entity Framework。控制员和视图大部分由EF脚手架。 RentalApplication和RentalObject之间的关系是1对多,这意味着RentalObject总是必须有1个RentalApplication。提交表单没有对所有的数据带来
我的控制器看起来是这样的:
// GET: /Calendar/Add/1
// Create a PartialView using a RentalObject as the model.
// Use the provided ID to lock in the RentalApplication.
[HttpGet]
public PartialViewResult Add(int id)
{
return PartialView(
new RentalObject(db.RentalApplicationSet.FirstOrDefault(x => x.Id == id)));
}
// POST: /Calendar/Add
// Save the submitted RentalObject to the db
[HttpPost]
public ActionResult Add(RentalObject rentalobject)
{
if (ModelState.IsValid)
{
try
{
db.RentalObjectSet.Add(rentalobject);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
我的目标是这样的:
public partial class RentalObject
{
public RentalObject()
{
this.Lease = new HashSet<Lease>();
}
public RentalObject(RentalApplication rentapp)
{
this.Lease = new HashSet<Lease>();
RentalApplication = rentapp;
PricePerHour = RentalApplication.DefaultPricePerHour;
Currency = RentalApplication.DefaultCurrency;
}
public int Id { get; set; }
public string Name { get; set; }
public bool IsAvailable { get; set; }
public string Illustration { get; set; }
public string Description { get; set; }
public decimal PricePerHour { get; set; }
public string Currency { get; set; }
public virtual ICollection<Lease> Lease { get; set; }
public virtual RentalApplication RentalApplication { get; set; }
}
所以,当我打开弹出窗口(使用@ Ajax.ActionLink拿到第一控制器添加行动)我创建一个RentalObject与RentalApplication(第二构造函数)用作模型。目前为止,弹出式对话框显示了RentalApplication中的PricePerHour和Currency值。
然而,当我在PartialView弹出提交表单一切都被复制,但RentalApplication对象。它以某种方式最终使用原始的RentalApplication中的PricePerHour和Currency创建一个新的RentalObject对象,但不包含RentalApplication属性下的对象本身。我的调试器甚至会转到RentalObject的第一个构造函数。
所以我想从控制器提交时查看(GET),并返回到控制器(POST)它有麻烦保持一个复杂对象的另一个对象中。这对我来说只是一个糟糕的做法吗?我应该使用ViewModel吗?
你渲染'RentalApplication'任何控制在你看来让他们回来后?是的它会使用第一(无参数)构造函数 - 这是怎么了'ModelBinder'作品 - 它使用反射来初始化这需要一个参数的构造函数一个新的实例(事实上,如果你删除它,它会抛出一个异常) – 2014-12-03 23:43:07