Creating Content Items using BuildEditor and a Controller

Topics: Writing modules
Sep 18, 2012 at 2:07 PM

Hi,

Building on sfmskywalkers tutorial on how to build a Webshop module, I am currently creating my own admin view for managing webshop products (as per Part 10 of the tutorial).  The tutorial shows how to create a list with search functionality as well as an edit form with post capability.  It lacks the delete function, but I figured that one out.

What's missing is the create method, which I have implemented like this:

        public ActionResult Create() {
            var product = _services.ContentManager.New("DoopsuikerProduct");            
            var model = _services.ContentManager.BuildEditor(product);
            return View(model);
        }

        [HttpPost, ActionName("Create")]
        public ActionResult CreatePost(DoopsuikerAdminCreate viewModel) {
            dynamic product = _services.ContentManager.New("DoopsuikerProduct");
            product.DoopsuikerProduct.Code = viewModel.Code;
            product.DoopsuikerProduct.Theme = viewModel.Theme;
            product.DoopsuikerProduct.Type = viewModel.Type;
            product.DoopsuikerProduct.Price = viewModel.Price;

            if (!ModelState.IsValid) {
                var model = _services.ContentManager.BuildEditor(product);
                return View(model);
            }
            
            _services.ContentManager.Create(product);
            _notifier.Add(NotifyType.Information, T("Your Product has been saved"));
            return RedirectToAction("Index");
        }
  

I seem to be unable to retrieve the posted editor data into my CreatePost method, while it is obviously there when I look at Request.Form using the debugger.  The viewmodel parameter above can't ever work as the properties do not map to the actual posted form, but I can't really believe that I need to build a full POCO object myself for posting, while I can simply use the BuildEditor functionality for rendering.  Can somebody help me out here?

Sep 18, 2012 at 3:25 PM

I found the answer myself, hidden in the Orchard.Blogs module's BlogAdminController:

        [HttpPost, ActionName("Create")]
        public ActionResult CreatePost() {
            dynamic product = _services.ContentManager.New("DoopsuikerProduct");
            _services.ContentManager.Create(product);
            dynamic model = _services.ContentManager.UpdateEditor(product, this);

            if (!ModelState.IsValid)
            {
                // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
                return View((object)model);
            }

            _services.ContentManager.Publish(product);
            _notifier.Add(NotifyType.Information, T("Your Product has been saved"));
            return RedirectToAction("Index");
        }