I want to submit a form (Html.BeginForm()) using JQuery Ajax. According to this question, it should work ! I don't understand why the parameters 'email' from the action SendEmail() doesn't get values from the js. Can you please help me ?
My View :
<% using (Html.BeginForm("SendEmail", null, FormMethod.Post, new { @class = "form", @id = "formSendMail" }))
{ %>
<fieldset>
<ul>
<li>
<label for="MailFrom">
De...</label>
<%= Html.TextBox("MailFrom", Session["email"].ToString(), new { @id = "MailFrom", @Name = "MailFrom", @readonly = "readonly" })%>
</li>
<li>
<label for="MailTo">
A...</label>
<%= Html.TextBoxFor(m => Model.Agent.Email, new { @id = "MailTo", @Name = "MailTo" })%>
</li>
<li>
<label for="MailSubject">
Objet :</label>
<%= Html.TextBoxFor(m => Model.MailSubject, new { @id = "MailSubject", @Name = "MailSubject" })%>
</li>
<li>
<label> </label>
<%= Html.TextArea("MailBody", Model.MailBody, 5, 10, null)%>
</li>
</ul>
</fieldset>
<% } %>
My controller :
[HttpPost]
public ActionResult SendEmail(Email email)
{
if (email != null)
{
if (!string.IsNullOrEmpty(email.MailBody) & !string.IsNullOrEmpty(email.Subject) & !string.IsNullOrEmpty(email.To))
{
using (IEmailDal emailDal = new EmailDal())
{
emailDal.SendEmail(email);
}
return Json("Email envoyé", JsonRequestBehavior.AllowGet);
}
else
return Json("Error");
}
else
return Json("Error");
}
My Email class :
public class Email
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string MailBody { get; set; }
}
To submit my form, I simulate the submit action via a button in jquery.dialog :
$("#mail-form").dialog({
buttons: {
"Envoyer le mail": function () {
$("#formSendMail").submit();
}
}
});
And my javascript :
$('#formSendMail').submit(function (e) {
var myEmail = {
From: $('#MailFrom').val(),
To: $('#MailTo').val(),
Subject: $('#MailSubject').val(),
MailBody: $('#MailBody').val()
};
$.ajax({
type: "POST",
url: '<%= Url.Action("SendEmail", "Messages") %>',
data: JSON.stringify(myEmail),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("Mail envoyé.");
},
error: function (result) {
alert("Echec lors de l'envoi du mail.");
}
});
return false;
});
Thank you !
contentType: "application/json; charset=utf-8",