我有一个 View 模型发送到我的 Controller 的编辑操作。 ViewModel 包含对 EntityObjects 的引用。 (是的,我很好,不需要复制 View 模型中的所有实体属性)。
我实例化 View 模型,然后调用 UpdateModel。我收到一个属性为“null”的错误,这很好,因为它是一个相关模型。我试图在模型绑定(bind)期间排除该属性的绑定(bind)。在调试它时,我在模型绑定(bind)器试图将属性值设置为 null 的实体中看到。
这是我的编辑操作:
var model = new SimplifiedCompanyViewModel(id);
var excludeProperties = new string[] {
"Entity.RetainedEarningsAccount.AccountNo"
,"Property.DiscountEarnedAccount.ExpenseCodeValue"
,"Entity.EntityAlternate.EntityID"
,"Property.BankAccount.BankAccountID"
,"Entity.PLSummaryAccount.AccountNo"
,"Property.RefundBank.BankAccountID"
,"Company.Transmitter.TCC"
};
try
{
UpdateModel<SimplifiedCompanyViewModel>(model, String.Empty, null, excludeProperties);
if (ModelState.IsValid)
{
//db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View(model);
}
我已经查看了有关指定“前缀”的其他一些问题,但我认为这不是问题,因为我告诉它绑定(bind)到 viewmodel 实例而不仅仅是实体对象。
我是否正确排除了属性?奇怪的是似乎只发生在这个项目上。我怀疑这可能是一个问题,因为实际上没有与我的实体相关的退款银行。但我有其他不存在的相关项目,也没有看到同样的问题。
更多信息......因为我被告知模型设计得不好。
该公司与一个银行账户有关。公司 View 显示当前相关的 BankAccount.BankAccountId,并且有一个带有 BankAccount.Key 的隐藏字段。 I use jQueryUI autocomplete feature to provide a dropdown of bank account displaying the BankAccount.BankAccountId and when one is selected the jQuery code changes the hidden field to have the correct Key value.因此,当发布此内容时,我不希望修改当前的银行帐户 BankAccountID,因此我希望它跳过绑定(bind)该字段。
如果我在模型中排除 BankAccountId,那么在 BankAccount 编辑 View 中,用户将永远无法更改 BankAccountId,因为它不会被绑定(bind)。我不确定这如何表明模型设计不佳。
最佳答案
我想出了一个非常简单的解决方案。
try
{
UpdateModel<SimplifiedCompanyViewModel>(model, String.Empty, null, excludeProperties);
ModelState.Remove("Entity.RetainedEarningsAccount.AccountNo");
ModelState.Remove("Property.DiscountEarnedAccount.ExpenseCodeValue");
ModelState.Remove("Entity.EntityAlternate.EntityID");
ModelState.Remove("Property.BankAccount.BankAccountID");
ModelState.Remove("Entity.PLSummaryAccount.AccountNo");
ModelState.Remove("Property.RefundBank.BankAccountID");
ModelState.Remove("ompany.Transmitter.TCC");
if (ModelState.IsValid)
{
//db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View(model);
}
关于asp.net-mvc-3 - 调用 UpdateModel() 时如何从绑定(bind)中排除属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8332594/