Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Dermot Curran 7 posts 99 karma points
    May 17, 2019 @ 15:40
    Dermot Curran
    0

    Creating parameterless constructor for custom ViewModels umbraco 8

    Hello Umbraco people,

    I tried to post back a form using a custom model to a surface controller and got 'No parameterless constructor defined for this object'. My model is as follows:

    public class ExampleViewModel : ContentModel
    {
        public ExampleViewModel(IPublishedContent content) : base(content){ }
    
        //properties etc...
    }
    

    My controller is as follows:

        public class ExampleSurfaceController : SurfaceController
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ExampleAction(ExampleViewModel model)
        {
            //do things
        }
    }
    

    I know from previous versions of umbraco this could be achieved by adding the following to the model:

    public ExampleViewModel () : base(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
    

    My question is, how is this achieved in Umbraco 8?

  • Søren Gregersen 441 posts 1884 karma points MVP 2x c-trib
    May 17, 2019 @ 17:21
    Søren Gregersen
    0

    Why do you require the submitted model to derive from content model?

  • Dermot Curran 7 posts 99 karma points
    May 20, 2019 @ 09:18
    Dermot Curran
    0

    I use it when rendering the view:

    public class ExampleController : RenderMvcController
    {
        [HttpGet]        
        public ActionResult ExampleAction(ContentModel contentModel)
        {
            var model = new ExampleViewModel(contentModel.Content);
    
            return CurrentTemplate(model);
        }
    }
    
  • Dermot Curran 7 posts 99 karma points
    May 20, 2019 @ 11:43
    Dermot Curran
    102

    Found the solution, by using the Umbraco.Web.Composing library and adding this constructor to my model:

    public ExampleViewModel() : base(Current.UmbracoHelper.AssignedContentItem){ }
    
  • Søren Gregersen 441 posts 1884 karma points MVP 2x c-trib
    May 20, 2019 @ 11:51
    Søren Gregersen
    0

    As long as you know what dependencies you are relying on :)

  • Dee 118 posts 338 karma points
    May 02, 2020 @ 16:16
    Dee
    1

    Saved my day!!

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies