MVC 3.0: re-saving object on post

MVC 3.0: re-saving object on post

Old forum URL: forums.lhotka.net/forums/t/10899.aspx


matt tag posted on Friday, November 18, 2011

working through learning MVC 3 and CSLA 4 all at the same time.  For fun, I decided to start programming in C# instead of VB.NET for the first time, too.  It's going.... uh, slow.

Working through the somewhat hack-tastic way you have to re-populate the business object from the changed form values when doing a save in MVC.  My business object has a somewhat unusual trait in that many of the properties are read-only when an object is EDITED - they are read-write on create only (the object represents a file attachment, so I don't want the user to be able to change the Upload date, Upload user, or the file data itself, as well as a primary and foreign key, only a few notes fields can be edited from here.

Since I have so many readonly fields, I had the brilliant idea that I would just re-get the object from the database during the post (instead of creating an "empty" one, and call UpdateModel and SaveObject.  This looks like it will work fine EXCEPT the object never saves - I'm assuming because IsDirty isn't set by UpdateModel.  Is there something that can work around this?

 

       [HttpPost]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            try
            {
                //re-get
                var mf = Med.Library.MedicalFile.GetObject(id);

                //update values
                UpdateModel(mf, collection);

                // save
                if (SaveObject<Med.Library.MedicalFile>(mf, true))
                    return RedirectToAction("Details", new { id = mf.PlayerID });
                else
                    return View();
            }
            catch
            {
                return View();
            }
        }

matt tag replied on Monday, November 21, 2011

this problem has been found and fixed.  I was using LoadProperty instead of SetProperty in my property declarations, so IsDirty was never getting set.

 

 

Copyright (c) Marimer LLC