Click here to Skip to main content
14,238,591 members
Rate this:
Please Sign up or sign in to vote.
See more:
Model is not valid and I cannot figure out why.

Model is below:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace PTPA.Models
{
        public class ContactUs
        {
            [Required]
            public string FirstName { get; set; }
            [Required]
            public string LastName { get; set; }
            [Required]
            [EmailAddress]
            public string Email { get; set; }
            [Required]
            public string Subject { get; set; }
            [Required]
            public string Message { get; set; }
        }
  }


View
And the front end is below:
@model PTPA.Models.ContactUs
@{
    ViewBag.Title = "ContactForm";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ContactForm</h2>

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<div>
    <div class="col-md-6">
        <div>
            @if (ViewBag.Message == null)
            {
                <div>
                    <form method="post">
                        <div class="form-group">
                            <label asp-for="FirstName">First Name</label>
                            <input asp-for="FirstName" class="form-control" />
                            <span asp-validation-for="FirstName"

                                  class="text-muted"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="LastName">Last Name</label>
                            <input asp-for="LastName" class="form-control" />
                            <span asp-validation-for="LastName"

                                  class="text-muted"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Email">Email</label>
                            <input asp-for="Email" class="form-control" />
                            <span asp-validation-for="Email"

                                  class="text-muted"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Subject">Subject</label>
                            <input asp-for="Subject" class="form-control" />
                            <span asp-validation-for="Subject"

                                  class="text-muted"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Message">Message</label>
                            <textarea rows="10" cols="10"

                                      asp-for="Message" class="form-control"></textarea>
                            <span asp-validation-for="Message"

                                  class="text-muted"></span>
                        </div>
                        <div>
                            <button type="Submit"

                                    class="btn btn-default">
                                Send Message
                            </button>
                        </div>

                    </form>
                </div>
            }
        </div>

        <div>
            <div>
                @if (ViewBag.Message != null)
                {
                    <div>@ViewBag.Message</div>


                }
            </div>
        </div>
    </div>

</div>
<div>END</div>


Controller class added by MadMyche
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using PTPA.Models;

namespace PTPA.Controllers {
	public class ContactController : Controller {
		// GET: Contact
		[HttpGet]
		public ActionResult ContactForm() {
			return View("ContactForm");
		}
		//Post : Contact
		[HttpPost]
		public ActionResult ContactForm(ContactUs cu) {
			if (ModelState.IsValid) {
				try {
					MailMessage msg = new MailMessage {
						From = new MailAddress(cu.Email)
					};
					msg.To.Add("donotreplyptpa@gmail.com");
					var fromEmailPassword = "example";
					msg.Subject = cu.Subject;
					msg.Body = "The following has been sent by a customer from the 'contact us' page. " + cu.Message;
					var smtp = new SmtpClient {
						Host = "smtp.gmail.com",
						Port = 587,
						EnableSsl = true,
						DeliveryMethod = SmtpDeliveryMethod.Network,
						UseDefaultCredentials = false

					};
					smtp.Credentials = new System.Net.NetworkCredential("example@gmail.com", fromEmailPassword);
					smtp.Send(msg);
					ModelState.Clear();
					ViewBag.Message = "Thank you for sending us your message, we value your response and aim to get back to you within 24 hours. Thank you.";
				}
				catch (Exception ex) {
					ModelState.Clear();
					ViewBag.Message = $" Something went wrong {ex.Message}";
				}
			}
			return View("ContactForm");
		}
		public ActionResult Error() {
			return View("ContactForm");
		}
	}
}


What I have tried:

I have tried changing and chopping the model but nothing has worked, i am new to this and only practicing so any help would be great.

Update: These are the values that are being used
FirstName:  Tom
LastName:   Allen
Email:      tomAllen@gmail.com
Subject:    TEST
Message:    TEST
Posted
Updated 27-Nov-18 19:46pm
v3
Comments
MadMyche 22-Nov-18 15:51pm
   
The Controller code would be helpful along with the values entered
MadMyche 22-Nov-18 18:30pm
   
When you see the updated question with this code and data, please delete the comment to keep it clean
MadMyche 22-Nov-18 19:10pm
   
How do you know the Model State is not valid? Debugging, not sending email, throwing an error?
Member 14063936 23-Nov-18 5:48am
   
When debugging it does not hit the 'try' section, hits the if and then breaks.
Richard Deeming 23-Nov-18 8:47am
   
Use the debugger to examine the ModelState dictionary. Drill down into the object, and you should see the list of errors, which should hopefully give you a clue.

View data values in DataTips in the code editor - Visual Studio | Microsoft Docs[^]
Rate this:
Please Sign up or sign in to vote.

Solution 2

The error typically means that your Model doesn't meet the requirements to be validated. In your example, your FirstName, LastName, Email, Subject and Message properties are decorated with the [Required] attribute. This means that those values shouldn't be null and empty otherwise your condition if(ModelState.IsValid) will be false.

To ensure that your model captures the data, I would suggest you to use the debugger, set a break-point at your ContactForm Action method and then step into your code. Check the variable cu and see if all the properties have values associated on it. Here's one reference that you can use to get started with debugging in Visual Studio: Learn to debug using the Visual Studio debugger - Visual Studio | Microsoft Docs[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

Use your HTMl form inside this BeginForm.
@using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post))
{
     
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100