Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Currently i trying to build a simple contact form.

My Contact.cshtml:
ASP.NET
<form asp-action="Contact" asp-controller="Root" method="post">
        <div>
            <label asp-for="Name">Please enter your name:</label>
            <input type="text" asp-for="Name" />
        </div>
        <div>
            <label asp-for="Email">Please enter your email:</label>
            <input type="text" asp-for="Email" />
        </div>
        <div>
            <label asp-for="Subject">Please enter a subject:</label>
            <textarea asp-for="Subject"></textarea>
        </div>
        <div>
            <label asp-for="Message">Please enter your message:</label>
            <textarea asp-for="Message"></textarea>
        </div>
        <input type="submit" value="Send Message!" />        
    </form>


My RootController:
ASP.NET
[HttpGet("contact")]
public IActionResult Contact()
{
     return View();
}

[HttpPost("contact")]
//[ValidateAntiForgeryToken]
public async Task<IActionResult> Contact([FromBody] ContactFormModel model)
{
  try
     {
      if (ModelState.IsValid)
      {
       var spamState = VerifyNoSpam(model);
       if (!spamState.Success)
       {
           return BadRequest(new { Reason = spamState.Reason });
       }       
       if (await _mailService.SendMailAsync("ContactTemplate.txt", model.Name, model.Email, model.Subject, model.Message))
       {
         return Ok(new { Success = true, Message = "Message Sent" });
       }

     }
   }
   catch (Exception ex)
   {
     _logger.LogError("Failed to send email from contact page", ex);
     return BadRequest(new { Reason = "Error Occurred" });
   }
     return BadRequest(new { Reason = "Failed to send email..." });
}


So i'm thinking, if i'm clicking the button, it should execute the "Contact" Action inside the Root-Controller.
I added a breakpoint on the Contact Action to see, if it works.

Sadly if i'm on my localhost/contact site, i'm getting just a blank page. Also it looks like the Contact Action aren't executed.

Maybe i have missed anything?

What I have tried:

The code on top. Also i read Part 6, controller methods and views in ASP.NET Core | Microsoft Docs[^]. The example there looks like mine.
Posted
Updated 12-Sep-21 9:41am
v3
Comments
Member 15329613 13-Sep-21 9:06am    
Where did you put your breakpoint? Put it on if (ModelState.IsValid)

Also inspect the html form that is generated and make sure it is posting to the correct url.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900