asp.net mvc3 UpdateModel exclude properties is not

2019-07-20 18:46发布

问题:

I have a class, which has 8 props / 8 columns in DB. But on a Edit page, i dont want to show the AddedDate or UserID field, since i dont want user to change it.

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; }
}

Here is what I have for Edit controller:

// 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);
}

On Edit page, once i click on submit, i got the following error: System.Data.SqlServerCe.SqlCeException: An overflow occurred while converting to datetime.

Seems like the AddedDate didn't get excluded from the view model and triggered the error.

Would you please let me know how to fix it? Thanks!

public ActionResult Edit([Bind(Exclude = "AddedDate")]Voucher voucher)

no luck either

回答1:

You are still passing in Voucher which could contain that field in it. I'm not sure what you are trying to accomplish with the UpdateModel here if you are already passing in a Voucher object? Pass in Voucher, set it to modified and save it. If you want to use whats in the database then you'll have to

  1. Load the object from the database
  2. UpdateModel and exclude the properties
  3. Save your entity.

You could simply use a View Model and post that.


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; }
}

and then load up your object from the db":


var voucher = db.Vouchers.Where(o=>o.ID==voucherViewModel.Id);
//manually copy the fields here then save it
//copy
db.SaveChanges();