Search code examples
asp.net-mvcmodel-view-controllerumbracomodels

Using custom Model in Umbraco - error?


I am getting the following error, when using my Custom model in Umbraco:

Cannot bind source type Umbraco.Web.Models.RenderModel to model type MyParser.Model.MyModel.

The code, which contains this model, is an old project i am 'importing' into a Umbraco site - it used to be just a vanilla MVC app.

For my use, it does not need to interact with Umbraco or the database - it just needs to live in the same project.

The layout, calling the model, looks like this;

@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyParser.Model.MyModel>
@{
    Layout = null;
}

The Model looks like this

namespace MyParser.Model
{
    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}

The code works fine in the vanilla MVC app, but needs to be modified to run inside an Umbraco-app it would seem - but how? It is Umbraco 7.6


Solution

  • If it is a document type template, you need to hijack the route to inject the view model. You create the controller that inherits from RenderMvcController and override Index method.

    namespace Controllers
    {
        public class [YourDocTypeAlias]Controller : RenderMvcController
        {
            public override ActionResult Index(RenderModel model)
            {
                var vm = new ViewModel<MyModel>(model);
                return View(vm);
            }
        }
    
        public class ViewModel<TModel> : RenderModel
        {
            public ViewModel(RenderModel model) : base(model.Content, model.CurrentCulture) { }
    
            public TModel CustomModel { get; set; }
        }
    
        public class MyModel
        {
            public string Name { get; set; }
            public string Value1 { get; set; }
            public bool IsValid { get; set; }
        }
    }
    

    and your template now becomes.

    @inherits Umbraco.Web.Mvc.UmbracoViewPage<ViewModel<MyModel>>
    @{
        Layout = "Master.cshtml";
        //you can now access properties from MyModel like Model.CustomModel.IsValid...
    }
    

    More info can be found on this link.