简体   繁体   中英

c# MVC Controller jsonresult action not found

I am creating a simple web page with aa simple purpose: for people to contact someone else. To do so, i have created a contract form like this:

<form id="mailForm" action="Contact/SendEmailAsync" method="post">

   @Html.AntiForgeryToken()

   <div class="form-group">
      @Html.TextBoxFor(model => model.FromName, htmlAttributes: new { @class = "form-control"})
   </div>
   <div class="form-group">
      @Html.TextBoxFor(model => model.FromEmail, htmlAttributes: new { @class = "form-control" })
   </div>
   <div class="form-group">
      @Html.TextBoxFor(model => model.EmailSubject, htmlAttributes: new { @class = "form-control" })
   </div>
   <div class="form-group">
      @Html.TextAreaFor(model => model.EMailBody, htmlAttributes: new { @class = "form-control", @cols = "30", @rows = "7" })
   </div>
<div class="form-group">
<id="formSubmit" type="submit" value="Verstuur bericht" class="btn btn-primary py-3 px-5">
</div>
</form>

I have also tried the razor shorthand version of action.

the submit button is linked to an ajax call as follows:

<script>
    $(document).ready(function () {
        var mailForm = $('mailForm')
        debugger;
        var data = mailForm.serialize()

        //get button by ID
        $('#formSubmit').submit(function () {
            debugger;
            //call a function with parameters
            $.ajax({
                url: '@Url.Action("SendEmailAsync", "Contact")',
                type: 'POST',
                timeout: '12000',
                contentType: "application/json; charset=utf-8",
                datatype: 'json',
                data: data,

            })
                .done(function () {
            console.log('done')});
    });
    });

</script>

Controller looks like this, but I never hit the breakpoint

namespace site.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ContactController : Controller
    {

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> SendEmailAsync(Mail mail)
        {
            {
                var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
                var message = new MailMessage();
                message.To.Add(new MailAddress("xxxxx"));  // replace with valid value 
                message.From = new MailAddress("xxxxx");  // replace with valid value
                message.Subject = "site contactformulier";
                message.Body = string.Format(body, mail.FromName, mail.FromEmail, mail.EMailBody); ;
                message.IsBodyHtml = true;

                using var smtp = new SmtpClient();
                var credential = new NetworkCredential
                {
                    UserName = "xxxx",  // replace with valid value
                    Password = "xxxxx"  // replace with valid value
                };
                smtp.Credentials = credential;
                smtp.Host = "smtp.xxxx.be";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                await smtp.SendMailAsync(message);
                return Json("ok");
            }
        }
    }
}

Error that i get is that my page is never found:

No webpage was found for the web address: https://localhost:44376/Contact/SendEmailAsync

What am i doing wrong?

Thanks in advance!

Can you please remove lines

[Route("api/[controller]")]
[ApiController]

And try again, I believe those are for API Controllers and may not work for MVC Controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM