开发者

How To Not Have ALL Fields On An Edit View But Not Get The 'Overflow while converting to datetime.'

开发者 https://www.devze.com 2023-03-20 05:13 出处:网络
I am somewhat new to MVC 3 so this could be something simple.I have a Compact SQL 4 database.There is a Post object that has a Contents (string), Subject (string), When (DateTime) and Reposted (DateTi

I am somewhat new to MVC 3 so this could be something simple. I have a Compact SQL 4 database. There is a Post object that has a Contents (string), Subject (string), When (DateTime) and Reposted (DateTime nullable) fields. During the Create's Post method, I manually force the When property to be DateTime.Now and it works great.

However, on my Edit View, I do NOT want to show this field or at least not let it be an editable field. When I do NOT put it as an editable field on the Edit View and they change say the Contents and then click Save I get the message:

An overflow occurred while converting to datetime.

During the Edit Postback, I am setting the Reposted field to DateTime.Now so it has to be the When field. When I debug on that postback I see that the "Post" object is only filled in with values of the fields I am displaying on the screen. So I decided to just grab the When field out with a LINQ query directly from the data but when I get to the 开发者_如何学CSaveChanges it fails and says the following:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

So how can I update an object and let the user only change a few pertinant fields? Seems like the Post object is not getting ALL of the existing values since they are not showing on the screen. How can I fill that object completely?

Edit: Here is the Post method.

[HttpPost]
public ActionResult Edit(Post post) {
  if (ModelState.IsValid) {
    db.Posts.Attach(post);

    int Successes = 0;
    int Failures = 0;

    this.SendEMail(post, out Successes, out Failures);
    post.Successes = Successes;
    post.Failures = Failures;
    post.Reposted = DateTime.Now;

    db.ObjectStateManager.ChangeObjectState(post, EntityState.Modified);
    db.SaveChanges();
    return RedirectToAction("Index");
  }

  return View(post);
}


Include a hidden field in your view for the fields that you do not want to display e.g.

@Html.HiddenFor(model => model.When)
0

精彩评论

暂无评论...
验证码 换一张
取 消