How to make this email form in C #?

0

I'm now starting to work with the default MVC asp.net, I created a view for contacts and in it insert a form that when filled in and clicked on the send button will go to my email, so I just made the frontend and did not I know how to do the rest, could anyone show me how this is done? Below the code of my form:

@{
    ViewBag.Title = "Contact";
}

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="w3-container w3-content w3-padding-64" style="max-width:800px">
    <h2 class="w3-wide w3-center">CONTATO</h2>
    <p class="w3-opacity w3-center"><i>Dúvidas? Contacte nosso suporte!</i></p>
    <div class="w3-row w3-padding-32">
        <div class="w3-col m6 w3-large w3-margin-bottom">
            <i class="fa fa-map-marker" style="width:30px"></i> São Gabriel da Palha, ES<br>
            <i class="fa fa-phone" style="width:30px"></i> Phone: 27 000 000 000<br>
            <i class="fa fa-envelope" style="width:30px"> </i> Email: [email protected]<br>
        </div>
        <div class="w3-col m6">
            <form action="#" target="_blank">
                <div class="w3-row-padding" style="margin:0 -16px 8px -16px">
                    <div class="w3-half">
                        <input class="w3-input w3-border" type="text" placeholder="Nome" required name="Nome">
                    </div>
                    <div class="w3-half">
                        <input class="w3-input w3-border" type="text" placeholder="Email" required name="Email">
                    </div>
                </div>
                <input class="w3-input w3-border" type="text" placeholder="Mensagem" required name="Mensagem">
                <button class="w3-button w3-black w3-section w3-right" type="submit">ENVIAR</button>
            </form>
        </div>
    </div>
</div>
    
asked by anonymous 23.01.2018 / 17:20

1 answer

2

For example, let's say this view is returned by the action Contatos() in HomeController . Create an overload for Contatos() by getting the parameters nome , email and mensagem adding annotation [HttpPost]

   [HttpGet]
    public ActionResult Contatos()
    {
        //Aqui retorna sua view com o o formulário
        return View();
    }

    [HttpPost]
    public ActionResult Contatos(string nome, string email, string mensagem)
    {
        //Faça validação adicional nos seus parâmetros de entrada
        if(!string.IsNullOrWhiteSpace(nome)&& !string.IsNullOrWhiteSpace(email)&&!string.IsNullOrWhiteSpace(mensgem))
        {
            //implemente o seu script para enviar o e-mail utilizando os parâmetros recebidos
            //ou chame o método que envia, caso você já tenha o feito
        }
        //Vai retornar para sua Contatos com o verbo [HttpGet]
        return View();
    }

Already in your view where the form is, you direct the post to Action that you created with the verb [HttpPost]

<form action="@Url.Action("Contatos","Home")" method="post">'

This is not just for emailing, it's a common MVC practice for CRUD solutions. Nevertheless, you could still create a ViewModel as well as being a good practice, it will bring many benefits and quality to your solution.

The simplest implementation would be as the example below:

public class ContatoViewModel
{
    public string Nome { get; set; }
    public string Email { get; set; }
    public string Mensagem { get; set; }
}

And your Action can receive the parameters as follows:

[HttpPost]
public ActionResult Contatos(ContatoViewModel contato)
{
   //...
}

But enriching ContatoViewModel with DataAnnotations and declaring it as the Model of your View and taking advantage of Helpers is that the joke is fun.

public class ContatoViewModel
{
    [Display(Name = "Nome: ", ShortName = "Nome")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Informe o seu nome")]
    [MinLength(3, ErrorMessage = "O seu nome deve possuir ao menos 3 caracteres")]
    [MaxLength(50, ErrorMessage = "O seu nome deve possuir no máximo 50 caracteres")]        
    public string Nome { get; set; }

    [Display(Name= "E-mail: ", ShortName = "E-mail")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Informe o seu E-mail")]
    [EmailAddress(ErrorMessage = "E-mail inválido")]
    public string Email { get; set; }

    [Display(Name= "Mensagem: ", ShortName = "Mensagem" )]
    [MaxLength(200, ErrorMessage = "A sua mensagem deve possuir no máximo 200 caracteres.")]        
    [Required(AllowEmptyStrings = false, ErrorMessage = "Escreva sua mensgem")]        
    public string Mensagem { get; set; }
}

Adding enriching your controller:

[HttpGet]
public ActionResult Contatos()
{            
    var model= new ContatoViewModel();
    //Enviando a ContatoViewModel como Model da sua View
    return View(model);
}

[HttpPost]
//Muito importante para tentar garantir que o post foi feito exclusivamente da sua view
[ValidateAntiForgeryToken]  
public ActionResult Contatos(ContatoViewModel contato)
{
    var model = new ContatoViewModel();

    //Validação obtida atráves das regras declaradas na ViewModel
    if(!ModelState.IsValid)
    {
        model = contato;                                
    }
    else
    {
        //implemente o seu script para enviar o e-mail utilizando os parâmetros recebidos
        //ou chame o método que envia, caso você já tenha o feito

    }

    return View(model);
}

And taking advantage of the Helpers in your View:

@{
    @model seu.namespace.ContatoViewModel
}

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="w3-container w3-content w3-padding-64" style="max-width:800px">
    <h2 class="w3-wide w3-center">CONTATO</h2>
    <p class="w3-opacity w3-center"><i>Dúvidas? Contacte nosso suporte!</i></p>
    <div class="w3-row w3-padding-32">
        <div class="w3-col m6 w3-large w3-margin-bottom">
            <i class="fa fa-map-marker" style="width:30px"></i> São Gabriel da Palha, ES<br>
            <i class="fa fa-phone" style="width:30px"></i> Phone: 27 000 000 000<br>
            <i class="fa fa-envelope" style="width:30px"> </i> Email: [email protected]<br>
        </div>
        <div class="w3-col m6">
            @using (Html.BeginForm("Contatos", "Home", FormMethod.Post))
            {
                @Html.AntiForgeryToken()

                <div class="w3-row-padding" style="margin:0 -16px 8px -16px">
                    <div class="w3-half">
                        @Html.TextBoxFor(m => m.Nome, new { @class = "w3-input w3-border" })                
                    </div>
                    <div class="w3-half">                        
                        @Html.TextBoxFor(m => m.Email, new { @class = "w3-input w3-border"})                
                    </div>
                </div>
                @Html.TextAreaFor(m => m.Mensagem, new { @class = "w3-input w3-border" })


                <button class="w3-button w3-black w3-section w3-right" type="submit">ENVIAR</button>
                <br />
                <div>
                    @Html.ValidationSummary(false, "", new { @class = "text-danger" })
                </div>
            }
        </div>
    </div>
</div>
    
24.01.2018 / 14:13