Malphai Malphai - 4 months ago 30
HTML Question

Validating Form in ASP.NET MVC C#

So as the title says, I am doing everything to get this validation to work, with RegEx and all, but it just wont work. What am I doing wrong here?

You dont need to type any data at all at the form, you can still send an empty mail, and I dont want that...

Model:

using System.ComponentModel.DataAnnotations;

namespace DK_Design.Models
{
public class SendMail
{
[Required]
public string Name { get; set; }

[Required]
public string Email { get; set; }

public string Number { get; set; }

[Required]
public string Message { get; set; }
}
}


View:

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
Kontakta
<strong>Oss!</strong>
</h2>
<hr>
</div>
<div class="col-md-8">

</div>
<div class="col-md-4">
<p>
Telefon:
<strong>123.456.7890</strong>
</p>
<p>
Email:
<strong><a href="mailto:*****@live.se">*****@live.se</a><!--I am obviously blurring the email on purpose here. The email function itself works.--> </strong>
</p>
<p>
Address:
<strong>
3481 Melrose Place
<br>Beverly Hills, CA 90210
</strong>
</p>
</div>
<div class="clearfix"></div>
</div>
</div>

<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
Skicka
<strong>Ett Meddelande</strong>
</h2>
<hr>
@if (ViewData["Message"] != null)
{
<div class="alert alert-success">Ditt e-mail har skickats!</div>
}
@if (ViewData["Message"] == null)
{
<div class="alert alert-danger">Ditt e-mail kan inte skickas!</div>
}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat, vitae, distinctio, possimus repudiandae cupiditate ipsum excepturi dicta neque eaque voluptates tempora veniam esse earum sapiente optio deleniti consequuntur eos voluptatem.</p>
<form class="form-wrapper" id="contact-form" method="post" role="form" novalidate>
<div class="form-group">
<div class="row">
<div class="form-group col-lg-4">
<label for="name">
Namn *
</label>
<input type="text" id="name" name="name" class="form-control" data-errmsg="Name is required."
placeholder="Ditt Namn" required />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="form-group col-lg-4">
<label for="email">
Email *
</label>
<input type="text" id="email" name="email" class="form-control" data-errmsg="Email is required."
placeholder="Ditt Email" required />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="form-group col-lg-4">
<label for="number">
Telefonnummer
</label>
<input type="text" id="number" name="number" class="form-control"
placeholder="Ditt Telefonnummer" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="form-group col-lg-8">
<label for="message">
Meddelande *
</label>
<textarea id="message" name="message" class="form-control" data-errmsg="Message is required."
placeholder="Ditt Meddelande" rows="3" required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2 col-sm-2 offset2">
<input style="font-size: 20px" type="submit" id="sendMail" value="Skicka" class="btn btn-primary" />
</div>
</div>
</form>
</div>
</div>
</div>
</div>


Controller:

using DK_Design.Models;
using System.Net.Mail;
using System.Web.Mvc;

namespace DK_Design.Controllers
{
public class KontaktController : Controller
{
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(SendMail input)
{
var mail = new MailMessage("*****", "*****");
var client = new SmtpClient("smtp-mail.outlook.com");
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
var credentials = new System.Net.NetworkCredential("*****", "*****");
client.EnableSsl = true;
client.Credentials = credentials;
mail.Body = input.Name + " " + input.Email + " " + input.Number + " " + input.Message;
mail.Subject = "Paket 1";
client.Send(mail);

ViewData["Message"] = mail;

return View(mail);

//Blurring the email information here too ofcourse.
}
}
}


I get the success message to pop up when email is sent, but not the other way around.

Answer

Your view model is decorated with Required data annotations. So you can use the inbuilt model validation.

[HttpPost]
public ActionResult Index(SendMail input)
{
  if(!ModelState.IsValid)
      return View(input);     
   //Your existing code here which sends email 

}

Make sure you have the relevant code for showing the vlaidation messages in your view. You may use the ValidationSummary or/and ValidationFor helper methods as needed. You may use the html helper methods to render the input fields as well. The helpers will generate the markup needed to show validation error messages.

@model SendMail    
@using(Html.BeginForm())
{
      @Html.LabelFor(s=>s.Name)
      @Html.TextBoxFor(s=>s.Name)
      @Html.ValidationMessageFor(t => t.Name)

      @Html.LabelFor(s=>s.Email)
      @Html.TextBoxFor(s=>s.Email)
      @Html.ValidationMessageFor(t => t.Email)

      @Html.LabelFor(s=>s.Number)
      @Html.TextBoxFor(s=>s.Number)
      @Html.ValidationMessageFor(t => t.Number)

      @Html.LabelFor(s=>s.Message)
      @Html.TextAreaFor(s=>s.Message)
      @Html.ValidationMessageFor(t => t.Message)

      <input type="submit" />
 }

Also i suggest you to follow the PRG pattern(Post-Redirect-GET). So instead of returning to the same view ,you will redirect to another GET action.

return RedirectToAction("EmailSent");
Comments