Dear Gurus,
Stuck on one thing and wondering if anyone on the forum could help me.
In this example, I'm creating an editableroot object, "trainer" in my Csla.Web.Mvc.Controller code. The DataPortal method on the server successfully inserts the record and updates its own ID field with the identity field generated by the database. However, back on the MVC side, the model is not being updated with the new ID.
What am I doing wrong here. Any help gratefully appreciated!
Justin.
Code follows:
[HttpPost]
public ActionResult Create(TrainerViewModel viewmodel)
{
if (ModelState.IsValid)
{
ValidateModel(viewmodel);
if (SaveObject<Library.Trainer>(viewmodel.ModelObject, false))
{
var id = viewmodel.ID; // NADA :(
return RedirectToAction("Index");
}
else
{
ViewData.Model = viewmodel;
return View();
}
}
return View();
}
Is your ID property read-only? As in, does it have a public setter?
I usually make my Id properties read-only, but for MVC you have to make all properties read-write (which is unfortunate, but it is what it is...)
Thank you for your response,
Yes - ID property already has a public set.
Is the updated business object definitely supposed to be returned after a DataPortal method? It doesn't appear to be, whatever I've done wrong. There is actually another field which I only set on Insert (a create date), but this is still blank on the business object when I examine it after the Controller SaveObject method is called. I think I've clearly messed it up somewhere but I'm having a hard time tracing the flow of data.
Justin.
The data portal Save method returns a new instance of the object. This is why you write code like this when directly calling save:
myObj = myObj.Save();
There's no way for the SaveObject method to update your local reference - it has no access to your 'viewmodel' variable.
What it updates is the ViewData.Model property. So within the success block where you don't see the value, you should do this first:
viewmodel = ViewData.Model;
Then your viewmodel variable will be referencing the correct object that was returned from the data portal.
So that's where it got to!
Thank you Rocky, works perfectly.
Copyright (c) Marimer LLC