Asp.net mvc 3 asp.net mvc3 UpdateModel排除属性不工作
我有一个类,在DB中有8个道具/8列。但在编辑页面上,我不想显示addedate或UserID字段,因为我不想让用户更改它Asp.net mvc 3 asp.net mvc3 UpdateModel排除属性不工作,asp.net-mvc-3,Asp.net Mvc 3,我有一个类,在DB中有8个道具/8列。但在编辑页面上,我不想显示addedate或UserID字段,因为我不想让用户更改它 public class Voucher { public int ID { get; set; } public string Title { get; set; } public string SiteName { get; set; } public string DealURL { get; set; } public Dat
public class Voucher
{
public int ID { get; set; }
public string Title { get; set; }
public string SiteName { get; set; }
public string DealURL { get; set; }
public DateTime AddedDate { get; set; }
public DateTime? ExpirationDate { get; set; }
public string VoucherFileURL { get; set; }
public Guid UserID { get; set; }
}
以下是编辑控制器的功能:
// POST: /Voucher/Edit/5
[HttpPost]
public ActionResult Edit(Voucher voucher)
{
if (ModelState.IsValid)
{
string[] excludeProperties = { "AddedDate", "UserID" };
UpdateModel(ModelState, "", null, excludeProperties);
db.Entry(voucher).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(voucher);
}
在“编辑”页面上,单击“提交”后,出现以下错误:System.Data.SqlServerCe.SqlCeException:转换为datetime时发生溢出
似乎AddedDate没有从视图模型中排除,并触发了错误
你能告诉我怎么修吗?谢谢
public ActionResult Edit([Bind(Exclude = "AddedDate")]Voucher voucher)
运气也不好您仍在传递可能包含该字段的凭证。如果您已经传入了凭证对象,我不确定您在这里使用UpdateModel想要完成什么? 传入凭证,设置为修改后保存。如果您想使用数据库中的内容,那么您必须
public class Voucher
{
public int ID { get; set; }
public string Title { get; set; }
public string SiteName { get; set; }
public string DealURL { get; set; }
public DateTime? ExpirationDate { get; set; }
public string VoucherFileURL { get; set; }
public Guid UserID { get; set; }
}
然后从数据库中加载对象”:
我想我误解了某些内容。我认为凭证对象与模型状态相同,它们都有8个属性。因此,我想在保存凭证时从模型状态中排除2个属性。如果验证模型,则没有模型状态。当您收到凭证时,MVC已对其进行验证并输出val结果升级到modelstate。您不会将其传递回updatemodel。当您希望使用发布值或URL值“更新某些模型对象”时,将使用updatemodel。在这种情况下,您已经获得了名为凭证的对象,其中包含这些属性。当用户编辑凭证时,我不允许他们查看或更改添加的日期或用户ID。因此传递到编辑控制器的凭证对象肯定不包含addedDate或UserID的值。因此,当凭证对象保存到db时,会触发错误。有解决方案吗?希望您理解。谢谢。尝试了以下操作,但没有成功:公共操作结果编辑([Bind(Exclude=“addedDate”)]凭证凭证然后创建一个名为VoucherEditViewModel的新模型对象。保留不希望看到的字段。是的,您正在将字段从凭证对象复制到此对象中。这不是“代码复制”,因为它们有不同的用途。此视图模型特定于您的屏幕。凭证对象是您的域对象。然后加载凭证r对象,将所需的值复制到数据库中,然后保存。另一种方法是使用UpdateModel(yourVoucherLoadedFromDb),但请注意,从理论上讲,您可以向最终用户公开他们不发布的值
var voucher = db.Vouchers.Where(o=>o.ID==voucherViewModel.Id);
//manually copy the fields here then save it
//copy
db.SaveChanges();