Tuesday, December 16, 2008

CSLA & ASP.NET MVC (part 3: Adding)

As I have mentioned previously in the last post, editing and adding is not that much different - one pulls an existing one and modify it with incoming data, the other is just creating a new instance and filling it up with incoming data. We discussed "editing" in my last post, and now we are going elaborate on "adding".

First, let's take a look on the displaying of the empty form. This one is pretty easy, just get a new customer and bind it into the model as CurrentCustomer.

public ActionResult New()

viewData.CurrentCustomer = Customer.NewCustomer();
viewData.CustomerList = CustomerInfoList.GetCustomerInfoList();
viewData.Titles = TitleInfoList.GetTitleInfoList();

return View("New", viewData);

We also want to bind the list of titles to be able to populate the drop down for title selection.

in handling the post, we are doing essentially the same thing as in edit, except this time we are mapping it to en empty object since it is a new one.
        [ActionName("New"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()
Customer customer = Customer.NewCustomer();
UpdateModel(customer, new[]
customer.DateEntered = DateTime.Now;
customer.DateUpdated = DateTime.Now;

if (!customer.IsValid)
foreach (Csla.Validation.BrokenRule brokenRule in customer.BrokenRulesCollection)
ModelState.SetAttemptedValue(brokenRule.Property, brokenRule.Property);
ModelState.AddModelError(brokenRule.Property, brokenRule.Description);
viewData.Titles = TitleInfoList.GetTitleInfoList();
viewData.CurrentCustomer = customer;
return View(viewData);
else {
TempData["Message"] = "I saved " + customer.LastName + " to the database";
return RedirectToAction("List", "Customer");
catch (Exception ex)
TempData["ErrorMessage"] = ex.Message;
return RedirectToAction("New");

So upon save, we want to display the confirmation message whether there is an error or the record is saved successfully. In the code above we also utilize CSLA rules validation - this is really useful in a way that we have a central place to put our format rules, business rules, validation at. If there is an error, we want to redisplay the new customer screen and if save is successful, we want to update the list with the current data.

Related Posts:
CSLA & ASP.NET MVC (part 1)
CSLA & ASP.NET MVC (part 2)

No comments: