Sunday 23 February 2014

Umbraco MVC - Partial View and Models


The model item passed into the dictionary is of type 'Umbraco.Web.Models.RenderModel', but this dictionary requires a model item of type 'UmbracoBaseFinal.Models.EnquiryModel'.

That is one annoying error, took me ages to find the solution, I knew what the problem is as it basically spells it out for you, but the solution was more difficult to find.  Anyway here it is.


In your main view you have a call like this to your partial view:


@Html.Partial("EnquiryForm", new EnquiryModel())
OR
 @Html.Partial("~/Views/Partials/EnquiryForm.cshtml", new EnquiryModel())


Which is all nice and simple.

Next we have the partial view, my example here, my Model has the properties for the contact form, but this

@inherits Umbraco.Web.Mvc.UmbracoViewPage

@using (Html.BeginUmbracoForm("HandleContactSubmit", "Enquiry"))
{
Enquiry Form

            @Html.LabelFor(x => Model.ContactName)
            @Html.TextBoxFor(x => Model.ContactName)
            @Html.ValidationMessageFor(x => Model.ContactName)
}

Your model should inherit from RenderModel, for example this is what I am using for my contact form at the moment.

using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.Models;

namespace UmbracoBaseFinal.Models
{
    public class EnquiryModel : RenderModel
    {
        [Required]
        public string
ContactName { get; set; }

        [Required]
        [RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "Enter a comment")]
        public string Comment { get; set; }

        public EnquiryModel() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
        public EnquiryModel(IPublishedContent content, CultureInfo culture) : base(content, culture) { }
        public EnquiryModel(IPublishedContent content) : base(content) { }
    }

}

No comments: