Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: ASP.NET MVC3
Hello,
 
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));
           }
       }
 
       [HttpPost]
       public ActionResult Edit(int id, DepartmentMaster dm)
       {
           try
           {
               using (var db = new TestEntities())
               {
                   db.Entry(dm).State = System.Data.EntityState.Modified;
                   db.SaveChanges();
                   return RedirectToAction("Index");
               }
           }
           catch
           {
               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.
Posted 3-Jan-13 4:11am
VIPR@T2.8K
Comments
rahkan at 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

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
v2

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

  Print Answers RSS
0 OriginalGriff 7,280
1 Sergey Alexandrovich Kryukov 6,059
2 Maciej Los 3,579
3 Peter Leow 3,383
4 CHill60 2,522


Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 3 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100