I am trying to get my head around models and controllers by trying to implement a basic contact form. Here's what I've done so far:
ContactFormViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ContactForm.Models
{
public class ContactFormViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
}
ContactFormController.cs
using ContactForm.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
namespace ContactForm.Controllers
{
public class ContactFormController : SurfaceController
{
[HttpPost]
public ActionResult SendMail(ContactFormViewModel model)
{
if (!ModelState.IsValid)
return CurrentUmbracoPage();
if (ModelState.IsValid)
{
string s;
s = $"<p>Name: {model.Name}</p> <p>Email: {model.Email}</p> <p>Message: {model.Message}</p>";
MailMessage msg = new MailMessage();
msg.From = new MailAddress("[email protected]");
msg.To.Add("[email protected]");
msg.Subject = "Message from WSHA contact form";
msg.Body = s;
msg.Priority = MailPriority.Normal;
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Send(msg);
}
return RedirectToCurrentUmbracoPage();
}
}
}
When I try to preview the page I have inserted the partial ContactForm.cshtml into I get this error message:
The model item passed into the dictionary is of type 'Umbraco.Web.Models.RenderModel', but this dictionary requires a model item of type 'ContactForm.Models.ContactFormViewModel'.
I've had a look at several posts on similar errors but I can't work out what's wrong here. Probably obvious but it's passing me by.
Wrong model item passed into dictionary
Hi,
I am trying to get my head around models and controllers by trying to implement a basic contact form. Here's what I've done so far:
ContactFormViewModel.cs
ContactFormController.cs
ContactForm.cshtml
When I try to preview the page I have inserted the partial ContactForm.cshtml into I get this error message:
I've had a look at several posts on similar errors but I can't work out what's wrong here. Probably obvious but it's passing me by.
Any help gratefully received, cheers, Alistair
Hi Alistair,
try the following:
Add a new action method into your controller like:
Make sure you have a folder called
ContactForm
in your views folder where you have yourContactForm.cshtml
.Then you can load in the partial view by using:
You can find more about locally declared surface controllers in the Umbraco docs:
https://our.umbraco.org/documentation/reference/routing/surface-controllers#locally-declared-controllers
Hope this helps.
/Michaël
Thank you Michael, that worked a treat.
Hi Alistair,
glad it solved your problem!
Have a nice day.
/Michaël
is working on a reply...