3

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>&nbsp;</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 !

7
  • 1
    Your form doesn't have a submit button Commented Oct 13, 2015 at 10:20
  • 2
    And as a side note - that answer is not strictly correct - you do not need to stringify the data if you remove contentType: "application/json; charset=utf-8", Commented Oct 13, 2015 at 10:24
  • @Coulton: It doesn't have a submit button because I'm using JQuery.Dialog, and I simulate the submit method via a button in the dialog : $("#mail-form").dialog({ autoOpen: false, width: 1140, modal: true, buttons: { "Envoyer le mail": function () { $("#formSendMail").submit(); } } }); Commented Oct 13, 2015 at 10:30
  • 1
    ok, when you use the developer tools (F12) in chrome, what information is being submitted? Commented Oct 13, 2015 at 10:31
  • @Stephen: IT WORKS !! Thank you so much !! I remove contentType and the stringify and now it's ok !! But I don't understand why !! Commented Oct 13, 2015 at 10:32

4 Answers 4

2

Here is the answer (thanks Stephen Muecke) :

I just need to remove contentType: "application/json; charset=utf-8",, then no need to stringify the data :

$.ajax({
    type: "POST",
    url: '<%= Url.Action("SendEmail", "Messages") %>',
    data: myEmail,
    dataType: "json",
    success: function (result) {
        alert("Mail envoyé.");
    },
    error: function (result) {
        alert("Echec lors de l'envoi du mail.");
    }
});

Now, why it didn't work in the first place, I don't know !

Sign up to request clarification or add additional context in comments.

Comments

0

if action method run correct ,your problem is the wrong path of the URLs .This is the correct URL's.

 url: '@Url.Action("SendEmail", "SampleController")',

the first parameter with called SendEmail is your action method,the second parameter is called SampleControl containing SendEmail method.

Comments

0

Why you are handling on submit event if this is on pop up button then handle it directly, I mean post it by Ajax directly and if you are using JSON.Stringify then on Action level handle it like this:

[HttpPost]
public ActionResult SendEmail(string email)
{
    Email formData = new JavaScriptSerializer().Deserialize<Email>(email);
    //Now you have the object handle it how you want
}

Comments

0

Please change the names of properties of email class same with the name of your textbox field name then you will get the values in controller.

public class Email
{
    public string MailFrom { get; set; }
    public string MailTo { get; set; }
    public string MailSubject { get; set; }
    public string MailBody { get; set; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.