How to make this email form in C#?

Asked

Viewed 116 times

0

I am starting now to work with the MVC standard Asp.net, I created a view for contacts and insert a form in it that when filled and clicked on the send button will go to my email, so I only did the frontend and do not know how to do the rest, Could someone 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>
  • You want that page to be inside the email, that’s it?

  • @Gabrielcoletta my question is, how will I call the sending function via the send button? How will I do the action of this button?? In PHP I’ve done this many times, more in C# will be the first... You got me figured out now????

  • Search a little, there are several tutorials teaching you how to email using C#. by your question, it seems you didn’t even try to do it before asking.

  • I know how to send guy, I don’t know how to do the action of the SEND button, that’s all I’d like to know!

  • 1

    I couldn’t understand... you don’t have an Action and a Controller to receive this form? Don’t know how to put in <form action="#"? Don’t know how to post via Ajax? Or don’t know how to send an email in C#? (which has nothing to do with this form)

  • @Leandroangelo Ready unintentionally you answered, what I need to do is put an action in the form by passing the file that contains the commands to send the email!!!

  • @Wpfan is not the file, it is the route you must pass.

  • @Leandroangelo for example!!

Show 3 more comments

1 answer

2


To illustrate, let’s say this view is returned by the action Contatos() in HomeController. Create an Overload for Contatos() receiving the parameters nome, email and mensagem adding the 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 you created with the verb [HttpPost]

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

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

The simplest implementation would be like 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 the ContatoViewModel with DataAnnotations and declaring her as the Model of his View and taking advantage of the Helpers is that the joke gets 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 enjoying 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>
  • Perfect guy, all right

  • 1

    I have added some complementary information for you to better understand other MVC features and from there, I believe you will have a basis to follow your studies.

  • Very good guy, you have a great knowledge, I’m starting now with MVC Asp.net... worked before with PHP dai to half lost hehehehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.