How to send POST data using AJAX? And how to get the POST data in the Web API?

In my MVC project, I need to send an HTML table as an email to a client.

I have an email function in the web API that I should name:

public class FunctionsController : ApiController
{
    [HttpPost]
    [Route("{controller}/email")]
    public void SendEmail(string to, string from, string body, string subject, string bcc)
    {
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = "xxxx";
        MailMessage mailMessage = new MailMessage();

        mailMessage.IsBodyHtml = true;
        mailMessage.Body = body;
        mailMessage.Subject = subject;
        mailMessage.From = new MailAddress(from);
        mailMessage.To.Add(new MailAddress(to));
        mailMessage.Bcc.Add(new MailAddress(bcc));

        smtpClient.Send(mailMessage);
    }

I am not sure how to do this.

This is my sendEmail javascript function in my MVC project (using Knockout):

   self.sendEmail = function (to, from, body, subject, bcc) {
    $.ajax({
        url: "../API/functions/email",
        type: "POST",
        data: {
            'to': to,
            'from': from,
            'body': body,
            'subject': subject,
            'bcc' : bcc
        },
        contentType: "application/json",
        success: function (data) {
           console.log(ko.toJSON(data));
        }
    });
}

How do I get POST data in a web API? Is javascript function correct?

Thanks in advance.

+4
source share
2 answers

It is always better to make a model / viewmodel.

public class EmailViewModel
{
    public string Body { get; set; }
    public string Subject { get; set; }
    public string From { get; set; }
    public string To { get; set; }
    public string Bcc { get; set; }
}

Now the controller method will look like this:

 public void SendEmail(EmailViewModel email)
  {
       .......
  }

and the ajax call will look like this:

 var email={
        'Body': body,
        'Subject': subject ,
        'From': from,
        'To': to,
        'Bcc': ''
   };
   $.ajax({
    url: "../xxx/functions/email/",
    type: "POST",
    data: email,
    contentType: "application/json",
    success: function (data) {
        callback(data);
    }
});

Hope this helps :)

+7

js:

    data: {
        'from_email': from,
        'to': to,
        'autotext': 'true',
        'subject': subject,
        'html': body
    },

:

public void SendEmail(string sBody, string sSubject, string sFrom, string sTo, string sBcc)

, MVC .

, , js .

, :

public void SendEmail(string html, string subject, string from_email, string to, string sBcc)
+4

All Articles