gpt4 book ai didi

c# - ASP.Net MVC,使用 JQuery.Ajax 提交表单

转载 作者:行者123 更新时间:2023-11-30 16:52:02 25 4
gpt4 key购买 nike

我想使用 JQuery Ajax 提交表单 (Html.BeginForm())。根据this question ,它应该工作!我不明白为什么 SendEmail() 操作中的参数“email”没有从 js 中获取值。你能帮帮我吗?

我的看法:

<% 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>
<% } %>

我的 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");
}

我的电子邮件类:

public class Email
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string MailBody { get; set; }
}

为了提交我的表单,我通过 jquery.dialog 中的按钮模拟提交操作:

$("#mail-form").dialog({
buttons: {
"Envoyer le mail": function () {
$("#formSendMail").submit();
}
}
});

还有我的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;
});

谢谢!

最佳答案

这是答案(感谢 Stephen Muecke):

我只需要删除 contentType: "application/json; charset=utf-8",,然后不需要对数据进行字符串化:

$.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.");
}
});

现在,为什么它一开始就不起作用,我不知道!

关于c# - ASP.Net MVC,使用 JQuery.Ajax 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33099755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com