Click here to Skip to main content
15,879,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I am new in MVC.
I am getting one problem. I am editing the record from the following code :

public ActionResult Edit(int id)
           using (var db = new TestEntities())
               return View(db.DepartmentMasters.Find(id));

       public ActionResult Edit(int id, DepartmentMaster dm)
               using (var db = new TestEntities())
                   db.Entry(dm).State = System.Data.EntityState.Modified;
                   return RedirectToAction("Index");
               return View();

Now when public ActionResult Edit(int id) this function is call i get the id . But when i edit the record and call this method public ActionResult Edit(int id, DepartmentMaster dm), i get the ID value 0, so i am not able to edit the record.

i am getting the following error:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
rahkan 3-Jan-13 15:02pm    
is id also the ID of the DepartmentMaster object? If so, then the id should be available inside of dm. If not, do you have any input controls in the form that are passing the id value when the form is submitted? You could use a hidden control for this.

1 solution

As was said, if the id is the id of the object being passed in, you have it already. Either way, the issue is in the code that does the Post, via a form I would guess for it to be getting a strongly typed object. Thus the issue is in the URL you are using, or it's in the global file, specifically the URL mappings.

Your code does not use the id anyhow. Your issue really is that your object is disconnected from your DB. You should use a viewmodel to get the data you want to edit, then in your Post action, look up the object, edit it and call SaveChanges. You should not be setting the state manually. All of this is broken.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900